user3892573
user3892573

Reputation: 23

Get integer from last 12 bits of 2 bytes in C#

I suspect this is an easy one.

I need to get a number from the first 4 bits and another number from the last 12 bits of 2 bytes.

So here is what I have but it doesn't seem to be right:

byte[] data = new byte[2];
//assume byte array contains data
var _4bit = data[0] >> 4;
var _12bit = data[0] >> 8 | data[1] & 0xff;

Upvotes: 2

Views: 2479

Answers (1)

quetzalcoatl
quetzalcoatl

Reputation: 33556

data[0]>>8 is 0. Remember that your data is defined as byte[] so it has 8bits per single item, so you are effectively cutting ALL bits off the data[0].

You want rather to take the lowest 4 bits from that byte by bitwise AND (00001111 = 0F) and then shift it leftwards as needed.

So try this:

var _4bit = data[0] >> 4;
var _12bit = ((data[0] & 0x0F) << 8) | (data[1] & 0xff);

It's also worth noting that the last & 0xFF is not needed, as the data[1] is already a byte.

On bits, step by step:

byte[2] data = { aaaabbbb, cccccccc }

var _4bit = data[0] >> 4;
          = aaaabbbb >> 4
          = 0000aaaa

var _12bit = ( (data[0] & 0x0F) << 8) | ( data[1] & 0xff);
           = ((aaaabbbb & 0x0F) << 8) | (cccccccc & 0xff);
           = (     0000bbbb     << 8) | (   cccccccc    );
           = (  0000bbbb000000000   ) | (   cccccccc    );
           =    0000bbbbcccccccc;

BTW. also, note that results of & and | operators are typed as int, so 32bits, I've omitted the zeroes for clarity and written it as 8bit only to make it brief!

Upvotes: 7

Related Questions