向左移位 3 如何得到以字节为单位的位数?

问题描述 投票:0回答:1

我正在学习位打包和位缓冲区,我遇到了这行代码

int NumBits = sizeof(float) << 3

现在输出是正确的,浮点数是 4 个字节,当你将其转换为位时,它是 32 位,这就是

NumBits

的值

我的问题是向左移位 3 位如何给出正确的值?

他们也可以用相反的方式做到这一点,将实际的

NumBits
向右移动 3

int numbytes = NumBits >> 3;
c++ c bit
1个回答
0
投票

sizeof(float) 返回浮点数的大小(以字节为单位)。在大多数系统(例如 PC)中,一个 float 为 4 个字节,因此 sizeof(float) 等于 4。

<< operator is the left shift operator. When you left-shift a value by a certain number of bits, you effectively multiply the value by 2 raised to the power of the number of bits shifted. In this case, you are left-shifting by 3 bits, so it's equivalent to multiplying by 2^3, which is 8.

所以,sizeof(float) << 3 is equivalent to 4 << 3, which is equal to 32. In summary, shifting to the left by 3 is same as multiplying with 8, which gives the number of bits.

© www.soinside.com 2019 - 2024. All rights reserved.