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

前端 未结 5 1040
陌清茗
陌清茗 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:46

    1. Yes, the most significant bit is usually written first. The left-most bit is labeled 7 because when the byte is interpreted as an integer, that bit has value 27 (= 128) when it is set.

    This is completely natural and is in fact is exactly the same as how you write decimal numbers (most significant digit first). For example, the number 356 is (3 x 102) + (5 x 101) + (6 x 100).

    2. For completion, as mentioned in other answers you can extract the individual values using the bit shift and bitwise-and operators as follows:

    int size = x & 7;
    int scale = (x >> 3) & 3;
    int precision = (x >> 5) & 7;
    

    Important note: this assumes that the individual values are to be interpreted as positive integers. If the values could be negative then this won't work correctly. Given the names of your variables, this is unlikely to be a problem here.

提交回复
热议问题