Home > C# > OverflowException while converting to Byte

OverflowException while converting to Byte

 string temp = “1000  255 255 0 243 8 50”;

string[] byteStrings = temp.Split(‘ ‘);

byte[] byteOut = new byte[byteStrings.Length];

for (int i = 0; i < byteStrings.Length; i++)

{

byteOut[i] = Convert.ToByte(byteStrings[i]);

}

While you are converting to byte by using above code, if the value you are converting is greater than 255 or less than 0 it throws an exception “System.OverflowException: Value was either too large or too small for an unsigned byte”

You can over come this problem by using encoding class, it will convert the unicode into a sequence of byte.

 string temp = “1000  255 255 0 243 8 50”;

string[] byteStrings = temp.Split(‘ ‘);

byte[] byteOut = new byte[byteStrings.Length];

for (int i = 0; i < byteStrings.Length; i++)

{

byte[] by1 = StrToByteArray(temp);

}

// C# to convert a string to a byte array.

public static byte[] StringToByteArray(string str)

{

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

return encoding.GetBytes(str);

}

To convert from byte format you can use the below code

public string bytToString(byte[] t)

{

// C# to convert a byte array to a string.

byte[] dBytes = t;

string str;

System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();

str = enc.GetString(dBytes);

return str;

}

Advertisements
Categories: C#
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: