Convert 12 bit int to 16 or 32 bits

11,724

Solution 1

32-bit:

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

Solution 2

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.

Solution 3

Detect the sign-bit and extend it. For 16-bit:

x = ( x & 0x800 ? x | 0xf000 : x );
Share:
11,724
Clarke76
Author by

Clarke76

Updated on July 22, 2022

Comments

  • Clarke76
    Clarke76 almost 2 years

    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.