prattom
prattom

Reputation: 1743

Converting 2 bytes to signed int

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

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

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

Kevin
Kevin

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

arrowd
arrowd

Reputation: 34401

Take a look at BitConverter class and its ToInt32() method.

Upvotes: 1

Related Questions