Reputation: 1743
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
Upvotes: 3
Views: 13853
Reputation: 186698
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));
Upvotes: 7
Reputation: 1472
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"
Upvotes: 10