C#,位&字节-如何从字节中检索位值? [英] C#, bits & bytes - How do I retrieve bit values from a byte?
问题描述
我正在从单个字节读取一些值.在用户手册中告诉我,这个字节包含3个不同的值.有一个看起来像这样的表:
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:
我解释说,精度占3位,小数位占2位,大小占3位,共8个(1字节).
I interpret that has meaning precision takes up 3 bits, scale takes up 2 and size takes up 3 for a total of 8 (1 byte).
我不清楚的是:
1-为什么将其标记为7到0而不是0到7(可能与重要性有关?)
1 - Why is it labeled 7 through 0 instead of 0 through 7 (something to do with significance maybe?)
2-如何从一个字节中提取单个值?
2 - How do I extract the individual values out of that one byte?
推荐答案
习惯上根据字节的重要性对字节进行编号:位 x
表示 2 ^ x
.根据这种编号方式,最低有效位的编号为零,下一位为编号,依此类推.
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).
具有与您要获取的位数相对应的最高编号的遮罩:1表示一位,3表示两位,7表示三位, 2 ^ x-1
x
位.
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.
这篇关于C#,位&字节-如何从字节中检索位值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!