12 bit conversion

  • Thread starter Thread starter Karel Vandenhove
  • Start date Start date
K

Karel Vandenhove

Hi,

I must convert a value that is stored in the first 12 bits (offset 0
to 11) of a block of data, to a number.

How can I do this in C#?

Kind regards,

Karel
 
Int32 is 32 bits, so you might either use a shift operation to left shift the 20
bits you don't want, then right shift back 20 to get your result. You could
also mask out the bits you want. 12 bits is 0xFFF hex. So you could do:

int myNumberShifted = (myData << 20) >> 20;
int myNumber = myData & 0xFFF;

I recommend the masking approach since it is invariant to the actual bit length
of an int.
 
Back
Top