运算符 << 是什么意思?从事这一行?
我无法理解这一行的作用:
fBuffer[fByteIndex] += 1 << (fBitIndex - 1);
where:
unsigned char fBuffer[32];
int fBitIndex;
and:
for ( int i = 0; i < 32; i++ )
fBuffer[i] = 0;
fBitIndex = 8;
那里有什么 <<
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
<<
是左移运算符,假设fBitIndex
为 8,代码相当于
Why?因为左移意味着将值的位“左移”;在您的例子中,
00000001
(1) 向左移动 7 次,变成10000000
(128)。<<
is the left-shift operator, and assumingfBitIndex
is 8 the codeis equivalent to
Why? Because a left-shift means you shift the bits of the value "left"; in your case,
00000001
(1), is shifted left 7 times, becoming10000000
(128).这称为位移位。每个字节由 8 位(0 或 1)组成。通过向左或向右移动一次,您可以将数字乘以 2 或除以 2。
It's called bit shifting. Each byte is composed of 8 bits (0 or 1). By shifting the bits one time to the left or the right you either multiply the number by 2 or divide it by 2.
这有点转变。十进制数 1 以二进制表示(仅显示低 8 位),
如果我有
,那么我将采用该数字并将其向左移动一位。然后我将得到二进制
,十进制值是 2。如果我有
,那么我会得到
十进制值 128。
It's a bit shift. The decimal number 1 is represented in binary (showing just the lower 8 bits) as
If I have
then I'll be taking that number and shifting it one place to the left. I'll then have the binary
which in decimal is the value 2. If instead I had
then I'd get
which in decimal would be 128.
它设置位 fBuffer[fByteIndex]
1 << N 只是位寻址。
<<是移位运算符,1<<0 是 0b1,1<<1 是 0b10 1<<6 是 0b1000000
因此,基于 fByteIndex 和 fBitIndex ,适当的位设置为 1。
在这种情况下,使用 + 的情况是寻址位已经是1,发生溢出,但我认为在你的代码中这不是这种情况,并且地址位在赋值之前是0。
It sets bit fBuffer[fByteIndex]
1 << N is just bit addressing.
<< is shift operator and 1<<0 is 0b1, 1<<1 is 0b10 1<<6 is 0b1000000
So based on fByteIndex and fBitIndex , propper bit is set on 1.
In this case where + is used in case that addressing bit is alredy 1, overflow occure, but I think that in your code this is not case and addresd bit is 0 before assignment.