这是我为大学解决的一项有趣的任务。
首先,我只允许使用以下运营商:! ~ & ^ | + << >>
(最多运营商:16)
我只能使用从0
到255
(0xFF
)的整数,而不是0xFFFF
或0xFFFFFFFF
)。
我明确禁止:
此外,我可以假设我的机器......
...使用两个补码和 32位整数表示。
......执行右移 算术
...当移动整数超过字数时,无法预测的行为。
我编写了一个名为bitMask(int highbit, int lowbit)
的函数,它生成一个整数,如下例所示:bitMask(5,3) = (0x38)16 = (0011 1000)2
(我已经删除了
这就是我提出的:
int bitMask(int highbit, int lowbit) {
//Calculates the number n, which we need to say how many times we have to shift Tmin2 to the right
int ptmHB = 31 + (~highbit + 1);
//Calculates the number m, which we need to say how many times we have to shift Tmin to the right
int ptmLB = 31 + (~lowbit + 1);
//Use TMin ((1000 ... 0000) a total of 31 zeros) to set all bits from the 31st bit to bit [31 - ptmHB]nth bit
int TMin = (1 << 31);
//If (ptmLB == 0), then we have to make TMin2 = 0 by shifting the MSB out (one to the right). Otherwise we keep TMin as it is.
int TMin2 = (TMin << !(ptmHB));
//If (TMin2 == 0), then the part before ^ falls away (only (TMin >> ptmLB) counts)
return (TMin2 >> ptmHB) ^ (TMin >> ptmLB);
}
但遗憾的是我仍然收到很多错误消息,当我在测试环境中尝试这个实现时,我必须在其中测试它:
Test bitMask(0[0x0],0[0x0]) failed. Gives 0[0x0]. Should be 1[0x1]
Test bitMask(0[0x0],1[0x1]) failed. Gives 1[0x1]. Should be 0[0x0]
Test bitMask(0[0x0],2[0x2]) failed. Gives 3[0x3]. Should be 0[0x0]
Test bitMask(0[0x0],3[0x3]) failed. Gives 7[0x7]. Should be 0[0x0]
Test bitMask(0[0x0],4[0x4]) failed. Gives 15[0xf]. Should be 0[0x0]
也许有人可以给我一个提示,因为我不确定我在这里做错了什么。在纸上,一切似乎都很好。