Converting 2 bytes to signed int
11,604
Solution 1
In case of one byte, just assign:
byte B1 = 0xFF;
int r = B1;
In case of two bytes - add shift and assign:
byte B1 = 0xFE;
byte B2 = 0xFC;
int r = (B1 << 8) | B2;
in case Int16
is wanted then cast:
// -260
short s = unchecked((short) ((B1 << 8) | B2));
Solution 2
Assuming the first byte is the msb:
byte b1 = 0xff;
byte b2 = 0xff;
var test = BitConverter.ToInt16(new byte[] { b1, b2 }, 0);
Otherwise:
byte b1 = 0xff;
byte b2 = 0xff;
var test = BitConverter.ToInt16(new byte[] { b2, b1 }, 0);
Edit: "signed"
Solution 3
Take a look at BitConverter class and its ToInt32() method.
Author by
prattom
Updated on June 22, 2022Comments
-
prattom about 2 years
Is their any way to convert 2 bytes to signed int? I know we can convert a byte to signed int in following way
byte B1= 0xFF; int r = Convert.ToSbyte((sbyte)B1);
but what about 2 bytes to signed int? For example -260 is 0xFC, 0xFE
-
prattom about 8 yearsThat will convert to unsigned integer
-
Groo about 8 yearsOP probably wants a signed
Int16
. -
default about 8 years@prattom BitConverter.ToInt32: Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array.
-
Groo about 8 yearsOP probably wants a signed
Int16
. -
prattom about 8 yearssorry not unsigned integer but Bitconverter returns positive integer instead to negative integer for ex. 0xFC, 0xFE is returned as 65276 if I use BitConverter class while it should -260
-
Gusman about 8 yearsgood old binary operators, for sure most efficient than any converter class :)
-
Thomas about 8 yearsToInt32(array<Byte>^, Int32) Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array. you should use this.
-
Gusman about 8 years@prattom that's becaue you used ToInt32 and only sent two bytes, an int32 has it's negative bit at the most significant bit of the dword, so there's no negative for two bytes, use ToInt16()