开发者

How to parse byte using bits value

开发者 https://www.devze.com 2023-02-05 15:05 出处:网络
I have to get values from a byte saved in three parts of bit combination. Bi开发者_开发问答t Combination is following

I have to get values from a byte saved in three parts of bit combination.

Bi开发者_开发问答t Combination is following

| - - | - - - | - - - |

first portion contains two bits Second portion contains 3 bits Third portion contains 3 bits

sample value is

11010001 = 209 decimal

What I want is create Three different Properties which get me decimal value of three portion of given bit as defined above.

how can i get Bit values from this decimal number and then get decimal value from respective bits..


Just use shifting and masking. Assuming that the two-bit value is in the high bits of the byte:

int value1 = (value >> 6) & 3;  // 3 = binary 11
int value2 = (value >> 3) & 7;  // 7 = binary 111
int value3 = (value >> 0) & 7;

The final line doesn't have to use the shift operator of course - shifting by 0 bits does nothing. I think it adds to the consistency though.

For your sample value, that would give value1 = 3, value2 = 2, value3 = 1.

Reversing:

byte value = (byte) ((value1 << 6) | (value2 << 3) | (value3 << 0));


You can extract the different parts using bit-masks, like this:

int part1=b & 0x3;
int part2=(b>>2) & 0x7;
int part3=(b>>5) & 0x7;

This shifts each part into the least-significant-bits, and then uses binary and to mask all other bits away.

And I assume you don't want the decimal value of these bits, but an int containing their value. An integer is still represented as a binary number internally. Representing the int in base 10/decimal only happens once you convert to string.

0

精彩评论

暂无评论...
验证码 换一张
取 消