Convert 12 bits int to 16 or 32 bits

So, I am reading a 12-bit integer from an array of bytes. This number may be negative, but I cannot figure out how to convert it to the useful variable int16 / int32 in C #. Keep in mind that I need to do something with bit offset or other bitwise operations, but for now I hit. Can someone point me in the right direction.

var x = 0xFFF;

It needs to be printed as -1, but C # naturally sends to int32 and displays it as 4095. If this requires int16 or int32 to be applied, how to save a negative value.

+5
source share
3 answers

32-bit:

x = (x >> 11) == 0 ? x : -1 ^ 0xFFF | x;
+13
source

, x - , 12- :

x = (x << 4) >> 4;

, . - -, . , >> - . , MSB , .

n m :

x = (x << (m - n)) >> (m - n);

m 8 sbyte, 16 short, 32 int 64 long. , . , .

+8
source

Detection of a sign and its extension. For 16-bit:

x = ( x & 0x800 ? x ^ 0xf000 : x );
0
source

All Articles