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;
}