Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 12 bit int to 16 or 32 bits

So I'm reading a 12 bit integer from a byte array. That number can be negative but I cant figure out how to convert that to a useable variable int16/int32 in c#. Have a feeling I'll need to do something with bit shifting or other bitwise operations but I've been striking out so far. Can someone point me in the right direction.

var x = 0xFFF;

This needs to prints out as -1 but c# naturally casts to an int32 and prints out as 4095. If this needs cast to int16 or int32 how do I preserve the negative value.

like image 284
Clarke76 Avatar asked Jun 04 '12 04:06

Clarke76


2 Answers

32-bit:

x = (x >> 11) == 0 ? x : -1 ^ 0xFFF | x;
like image 85
Andrew Cooper Avatar answered Nov 04 '22 01:11

Andrew Cooper


Sign extension without conditionals, assuming x is a signed short already containing the 12 bit value:

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

The parentheses are purely for understanding what's going on. Bit shifts are left-associative like other arithmetical and logical operators. The reason why this works is that >> is an arithmetic right shift for signed types. That means, instead of shifting in zeroes at the most significant bit, it duplicates the MSB as many times as necessary.

Sign extension in general from n bit to m bit would then be:

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

For obvious reasons m would be restricted to 8 for sbyte, 16 for short, 32 for int and 64 for long. Again, parentheses are purely cosmetic. Subtraction binds tighter than bit shifts.

like image 40
Wormbo Avatar answered Nov 04 '22 02:11

Wormbo