错误的位移结果
Wrong bitshift results
我是第一次使用 bitshift,结果出乎意料。
我声明的转移金额如下:
byte p_size = 0;
if (ver == 0x12 || ver == 0x13)
p_size = 20;
else
p_size = 40;
要移动的值声明为
int t_size = rinput.ReadInt32();
最后是我用来转换的代码:
int temp = t_size >> p_size << p_size;
假设 t_size = 0x2000385E 和 p_size = 20.temp = 0x20000000 正如预期的那样。
现在如果 t_size = 0x40001014 且 p_size = 40,temp = 0x40001000 而不是 0x40000000。我使用按位计算器计算了 "manually",它与 0x40000000 的预期结果相匹配。
这对我来说可能是一个愚蠢的疏忽,但我不明白什么会导致 p_size = 40 的奇怪结果...欢迎任何建议!
将 32 位整数移动 40 位实际上没有意义,因为您会将整数移动的位数多于它包含的位数。
两个 left and right 移位运算符都记录了他们在这种情况下所做的事情:
If the first operand is an int or uint (32-bit quantity), the shift
count is given by the low-order five bits of the second operand
(second operand & 0x1f).
所以当 p_size
为 40 时,班次移动 40 & 0x1f = 8 bits.
如果你需要移位40位,但是你的值变成了long
。
当前行为是预期的,因为 40 和 0x1f 是 8,如 operator >>
中所述
If the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand (second operand & 0x1f).
您可能正在寻找一些掩蔽而不是转变 - 也许
t_size & 0xFF000000
我是第一次使用 bitshift,结果出乎意料。
我声明的转移金额如下:
byte p_size = 0;
if (ver == 0x12 || ver == 0x13)
p_size = 20;
else
p_size = 40;
要移动的值声明为
int t_size = rinput.ReadInt32();
最后是我用来转换的代码:
int temp = t_size >> p_size << p_size;
假设 t_size = 0x2000385E 和 p_size = 20.temp = 0x20000000 正如预期的那样。
现在如果 t_size = 0x40001014 且 p_size = 40,temp = 0x40001000 而不是 0x40000000。我使用按位计算器计算了 "manually",它与 0x40000000 的预期结果相匹配。
这对我来说可能是一个愚蠢的疏忽,但我不明白什么会导致 p_size = 40 的奇怪结果...欢迎任何建议!
将 32 位整数移动 40 位实际上没有意义,因为您会将整数移动的位数多于它包含的位数。
两个 left and right 移位运算符都记录了他们在这种情况下所做的事情:
If the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand (second operand & 0x1f).
所以当 p_size
为 40 时,班次移动 40 & 0x1f = 8 bits.
如果你需要移位40位,但是你的值变成了long
。
当前行为是预期的,因为 40 和 0x1f 是 8,如 operator >>
中所述If the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand (second operand & 0x1f).
您可能正在寻找一些掩蔽而不是转变 - 也许
t_size & 0xFF000000