C#, bits & bytes - How do I retrieve bit values from a byte?

前端 未结 5 1004
陌清茗
陌清茗 2020-12-29 08:04

I\'m reading some values from a single byte. I\'m told in the user-manual that this one byte contains 3 different values. There\'s a table that looks like this:

5条回答
  •  隐瞒了意图╮
    2020-12-29 08:24

    It is customary to number bits in a byte according to their significance: bit x represents 2^x. According to this numbering scheme, the least significant bit gets number zero, the next bit is number one, and so on.

    Getting individual bits requires a shift and a masking operation:

    var size = (v >> 0) & 7;
    var scale = (v >> 3) & 3;
    var precision = (v >> 5) & 7;
    

    Shift by the number of bits to the right of the rightmost portion that you need to get (shifting by zero is ignored; I added it for illustration purposes).

    Mask with the highest number that fits in the number of bits that you would like to get: 1 for one bit, 3 for two bits, 7 for three bits, 2^x-1 for x bits.

提交回复
热议问题