Convert Int to Byte in C#

Muhammad Zeeshan Feb 11, 2022
  1. Use the ToByte(String) Method to Convert Int to Byte[] in C#
  2. Use the ToByte(UInt16) Method to Convert Int to Byte[] in C#
  3. Use the ToByte(String, Int32) Method to Convert Int to Byte[] in C#
Convert Int to Byte in C#

We’ll look at a few different techniques to convert Int to Byte[] in C#.

Use the ToByte(String) Method to Convert Int to Byte[] in C#

This approach works by converting the provided string representation of a number to an equivalent 8-bit unsigned integer using the ToByte(String) method. It takes as a string argument, containing the number to convert.

The example below creates a string array and converts each string to a Byte.

First, add these libraries.

using System;
using System.Diagnostics;

We begin by creating a string[] type variable called Alldatavalues and assigning some values.

string[] Alldatavalues = {null,"","3227","It5","99","9*9","25.6","$50","-11","St8"};

Now use a for each loop to convert integer to byte using Convert.ToByte().

byte num = Convert.ToByte(value);

A format exception occurs (0 through 9) when a value does not have an optional sign followed by a series of numbers. We utilize the FormatException handler to overcome this.

catch (FormatException) {
  Console.WriteLine("Unsuported Format: '{0}'",value == null ? "<null>" : value);}

An overflow error arises when a value reflects lesser than MinValue or greater than MaxValue.

catch (OverflowException) {
  Console.WriteLine("Data Overflow Exception: '{0}'", value);}

Source code:

using System;
using System.Diagnostics;

public class ToByteString
{
   public static void Main()
   {
      string[] Alldatavalues = {null,"","3227","It5","99","9*9","25.6","$50","-11","St8"};
      foreach (var value in Alldatavalues) {
         try {
            byte num = Convert.ToByte(value);
            Console.WriteLine("'{0}' --> {1}",value == null ? "<null>" : value, num);
         }
         catch (FormatException) {
            Console.WriteLine("Unsupported Format: '{0}'",value == null ? "<null>" : value);
         }
         catch (OverflowException) {
            Console.WriteLine("Data Overflow Exception: '{0}'", value);
         }
      }
   }
}

Output:

'<null>' --> 0
Unsupported Format: ''
Data Overflow Exception: '3227'
Unsupported Format: 'It5'
'99' --> 99
Unsupported Format: '9*9'
Unsupported Format: '25.6'
Unsupported Format: '$50'
Data Overflow Exception: '-11'
Unsupported Format: 'St8'

Use the ToByte(UInt16) Method to Convert Int to Byte[] in C#

ToByte(UInt16) method converts the value of a 16-bit unsigned integer to an 8-bit unsigned integer equivalent. To convert, it requires a 16-bit unsigned integer as an argument.

In the following example, an array of unsigned 16-bit integers is converted to Byte values.

Libraries to be added are:

using System;
using System.Diagnostics;

First, initialize a ushort[] type variable named data; after that, we’ll assign some value to it like UInt16.MinValue as a minimum value, UInt16.MaxValue as the maximum value and other values that we want to convert like we have inserted 90 and 880.

ushort[] data = { UInt16.MinValue, 90, 880, UInt16.MaxValue };

Then we’ll create a byte type variable named result.

byte result;

After that, apply a foreach loop which will convert data in Byte type; other than that, if a number exceeds the range of Byte, it will show an exception.

foreach (ushort numberdata in data)
{
 try{
     result = Convert.ToByte(numberdata);
     Console.WriteLine("Successfully converted the {0} value {1} to the {2} value {3}.",numberdata.GetType().Name, numberdata,result.GetType().Name, result);
   }
   catch (OverflowException) {
      Console.WriteLine("The {0} value {1} is outside the range of Byte.",numberdata.GetType().Name, numberdata);
   }
}

Source Code:

using System;
using System.Diagnostics;

public class ToByteString
{
  public static void Main()
   {
    ushort[] data = { UInt16.MinValue, 90, 880, UInt16.MaxValue };
    byte result;

foreach (ushort numberdata in data)
{
 try{
     result = Convert.ToByte(numberdata);
     Console.WriteLine("Successfully converted the {0} value {1} to the {2} value {3}.",numberdata.GetType().Name, numberdata,result.GetType().Name, result);
   }
   catch (OverflowException) {
      Console.WriteLine("The {0} value {1} is outside the range of Byte.",numberdata.GetType().Name, numberdata);
   }
}
   }
}

Output:

Successfully converted the UInt16 value 0 to the Byte value 0.
Successfully converted the UInt16 value 90 to the Byte value 90.
The UInt16 value 880 is outside the range of Byte.
The UInt16 value 65535 is outside the range of Byte.

Use the ToByte(String, Int32) Method to Convert Int to Byte[] in C#

This method converts a number’s string representation to an equivalent 8-bit unsigned integer in a given base. It takes a string parameter value containing the number to be converted.

The following libraries will be added.

using System;
using System.Diagnostics;

First, we’ll construct an int[] type variable called Allbasedata and assign the bases 8 and 10.

int[] Allbasedata = { 8, 10 };

Now we create a string[] type variable called values and assign values to it, and declare a byte type variable called number.

string[] values = { "80000000","1201","-6", "6", "07", "MZ", "99" , "12", "70", "255" };
byte number;

Then we’ll apply a foreach loop in which it converts the number to byte format, and it will also handle exceptions like:

  1. FormatException: This error occurs when the value contains a character that is not a valid digit in the base supplied by from base.
  2. OverflowException: This error occurs when a negative sign is prefixed to a value representing a base 10 unsigned number.
  3. ArgumentException: This error occurs when the value is empty.
foreach (string value in values){
  try {
        number = Convert.ToByte(value, numberBase);
        Console.WriteLine("   Converted '{0}' to {1}.", value, number);
      }
  catch (FormatException) {
        Console.WriteLine("   '{0}' is an Invalid format for a base {1} byte value.", value, numberBase);
      }
  catch (OverflowException) {
        Console.WriteLine("   '{0}' is Outside the Range of Byte type.", value);
      }
  catch (ArgumentException) {
        Console.WriteLine("   '{0}' is invalid in base {1}.", value, numberBase);
      }
}

Source Code:

using System;
using System.Diagnostics;

public class ToByteStringInt32
{
  public static void Main()
   {
    int[] Allbasedata = { 8, 10 };
    string[] values = { "80000000","1201","-6", "6", "07", "MZ", "99" , "12", "70", "255" };
    byte number;
     foreach (int numberBase in Allbasedata)
      {
        Console.WriteLine("Base Number {0}:", numberBase);
        foreach (string value in values)
         {
            try {
               number = Convert.ToByte(value, numberBase);
               Console.WriteLine("   Converted '{0}' to {1}.", value, number);
            }
            catch (FormatException) {
               Console.WriteLine("   '{0}' is an Invalid format for a base {1} byte value.", value, numberBase);
            }
            catch (OverflowException) {
               Console.WriteLine("   '{0}' is Outside the Range of Byte type.", value);
            }
            catch (ArgumentException) {
               Console.WriteLine("   '{0}' is invalid in base {1}.", value, numberBase);
            }
         }
      }
   }
}

Output:

Base Number 8:
   '80000000' is an Invalid format for a base 8 byte value.
   '1201' is Outside the Range of Byte type.
   '-6' is invalid in base 8.
   Converted '6' to 6.
   Converted '07' to 7.
   'MZ' is an Invalid format for a base 8 byte value.
   '99' is an Invalid format for a base 8 byte value.
   Converted '12' to 10.
   Converted '70' to 56.
   Converted '255' to 173.
Base Number 10:
   '80000000' is Outside the Range of Byte type.
   '1201' is Outside the Range of Byte type.
   '-6' is Outside the Range of Byte type.
   Converted '6' to 6.
   Converted '07' to 7.
   'MZ' is an Invalid format for a base 10 byte value.
   Converted '99' to 99.
   Converted '12' to 12.
   Converted '70' to 70.
   Converted '255' to 255.
Muhammad Zeeshan avatar Muhammad Zeeshan avatar

I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I'm a senior in an undergraduate program for a bachelor's degree in Information Technology.

LinkedIn

Related Article - Csharp Int

Related Article - Csharp Conversion