Reputation: 29
I have a code that returns array of bytes which could be one byte or more or less. The problem relies in that when I convert the bytes some times I get an error because I can't determine when I need to use toInt32, toInt64, or toInt16. The other problem is that sometimes when I get one byte I am not able to convert this byte using these above methods because I keep getting errors. So how to determine based maybe on the length or size of bytes which method I should use.
//as in array of bytes byte[]
var response = this.cc.Sendcc("SERIAL_NUMBER", 0x05, 0x80, 0x64, 0x04, 0x01, 0x21, (byte)1, (byte)1);
if (response .Length == 1)
{
toInt32SerialNumber = BitConverter.ToInt16(response , 0);
}
else
{
toInt32SerialNumber = BitConverter.ToInt32(response , 1);
}
Upvotes: 0
Views: 967
Reputation: 497
Try following, it will handle all possible values/bytes of "response":
if(response.Length<8)
{
byte[] temp = new byte[8];
response.CopyTo(temp, 0);
response = temp;
}
UInt64 toInt32SerialNumber = BitConverter.ToUInt64(response, 0);
Further, StartIndex should be zero unless you need to skip some data intentionally!
Upvotes: 0
Reputation: 967
@moe1792
Please try this code,To convert bytes array to an int using bit converter in c#:
byte[] bytes = { 0, 0, 0, 25 };
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int : {0}", i);
I hope above code will be useful for you.
Thank you.
Upvotes: 0