我想在Java中执行以下两种位移,但不知道我该怎么做,是否有人可以提供一些提示?
**Case one:**
e.g original number in binary is "101"
left shift and put a "1" on the right most
left shift: "011"
left shift again : "111"
似乎这种情况可以通过"(数字<< 1)|来完成1"
**Case two:**
e.g original number in binary is "101"
left shift and put a "0" on the right most
left shift: "010"
left shift again: "100"
但不确定如何做第二种情况。我试过"(数字<< 1)& 0",但它将整个事情变为0。
答案 0 :(得分:0)
使用掩码,例如:
int MASK = 0x7; // three 1s at the LSD
int myVar = 0x5; // 101 in binary
int myResult;
...
myResult = ((myVar << 1) | 1) & MASK; // to add 1 in the LSD
...
myResult = ((myVar << 1)) & MASK; // to add 0 in the LSD