问题描述
低级别位操作从来都不是我的强项。我将非常感谢理解以下bitwise运算符的用例.Consider ...
Low level bit manipulation has never been my strong point. I will appreciate some help in understanding the following use case of bitwise operators.Consider...
int age, gender, height, packed_info;
. . . // Assign values
// Pack as AAAAAAA G HHHHHHH using shifts and "or"
packed_info = (age << 8) | (gender << 7) | height;
// Unpack with shifts and masking using "and"
height = packed_info & 0x7F; // This constant is binary ...01111111
gender = (packed_info >> 7) & 1;
age = (packed_info >> 8);
我不确定这段代码是完成的以及如何完成?为什么要使用幻数0x7F?如何完成包装和拆包?
I am not sure what this code is accomplishing and how? Why use the magic number 0x7F ? How is the packing and unpacking accomplished?
推荐答案
正如评论所说,我们将把年龄,性别和身高打包成15位,格式为:
As the comment says, we're going to pack the age, gender and height into 15 bits, of the format:
AAAAAAAGHHHHHHH
让我们从这一部分开始:
Let's start with this part:
(age << 8)
首先,年龄有以下格式:
To start with, age has this format:
age = 00000000AAAAAAA
其中每个A可以是0或1。
where each A can be 0 or 1.
<< 8
将位移到左侧8位,并用零填充间隙。所以你得到:
<< 8
moves the bits 8 places to the left, and fills in the gaps with zeroes. So you get:
(age << 8) = AAAAAAA00000000
同样:
gender = 00000000000000G
(gender << 7) = 0000000G0000000
height = 00000000HHHHHHH
现在我们要将这些组合成一个变量。 |
运算符通过查看每个位来工作,如果任一输入中的位为1,则返回1。所以:
Now we want to combine these into one variable. The |
operator works by looking at each bit, and returning 1 if the bit is 1 in either of the inputs. So:
0011 | 0101 = 0111
如果一个输入中的位为0,则从另一个输入中获取该位。查看(年龄,
(性别<<<<<<<<<<<<<<<<<<<<<&n; c> height
,您会看到,如果其中一个位为1,则其他位为0。所以:
If a bit is 0 in one input, then you get the bit from the other input. Looking at
(age << 8)
, (gender << 7)
and height
, you'll see that, if a bit is 1 for one of these, it's 0 for the others. So:
packed_info = (age << 8) | (gender << 7) | height = AAAAAAAGHHHHHHH
现在我们要解包这些位。让我们从高度开始吧。我们想得到最后7位,并忽略前8位。为此,我们使用
&
运算符,只有当两个输入位都是1.所以:
Now we want to unpack the bits. Let's start with the height. We want to get the last 7 bits, and ignore the first 8. To do this, we use the
&
operator, which returns 1 only if both of the input bits are 1. So:
0011 & 0101 = 0001
所以:
packed_info = AAAAAAAGHHHHHHH
0x7F = 000000001111111
(packed_info & 0x7F) = 00000000HHHHHHH = height
为了获得年龄,我们可以将所有8个位置向右推,我们留下
0000000AAAAAAAA
。所以年龄=(packed_info>> 8)
。
To get the age, we can just push everything 8 places to the right, and we're left with
0000000AAAAAAAA
. So age = (packed_info >> 8)
.
最后,为了获得性别,我们推动一切7个地方向右摆脱高度。然后我们只关心最后一点:
Finally, to get the gender, we push everything 7 places to the right to get rid of the height. We then only care about the last bit:
packed_info = AAAAAAAGHHHHHHH
(packed_info >> 7) = 0000000AAAAAAAG
1 = 000000000000001
(packed_info >> 7) & 1 = 00000000000000G
这篇关于使用按位运算符在一个int中打包多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!