简体   繁体   中英

How to convert bytes to an int using bit converter in c#

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

@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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM