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.
32-bit:
x = (x >> 11) == 0 ? x : -1 ^ 0xFFF | x;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With