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.

Share:
11,604
prattom
Author by

prattom

Updated on June 22, 2022

Comments

  • prattom
    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
    prattom about 8 years
    That will convert to unsigned integer
  • Groo
    Groo about 8 years
    OP probably wants a signed Int16.
  • default
    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
    Groo about 8 years
    OP probably wants a signed Int16.
  • prattom
    prattom about 8 years
    sorry 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
    Gusman about 8 years
    good old binary operators, for sure most efficient than any converter class :)
  • Thomas
    Thomas about 8 years
    ToInt32(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
    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()