我有以下现有的整数:
128 = 1000.0000
我想将下面的整数转移到左边2个位置......
15 = 0000.1111
...将现有数字转换为bitindex 6:
MyResult
应为= 1011.1100 = 188
我试过这个,但结果是错的。如果我将positionsToShift
更改为2:
int existingNumber = 128;
int numberToLeftShift = 15;
int positionsToShift = 6;
int myResult = (existingNumber << positionsToShift) | numberToLeftShift;
答案 0 :(得分:4)
根据您的解释,您希望numberToLeftShift
转移
15 << 2
然后anf与现有整数结合使用:
(15 << 2) | 128
实施
int existingNumber = 128;
int numberToLeftShift = 15;
int positionsToShift = 2; // we want shift by 2 to the left; not by 6
// numberToLeftShift and existingNumber are swapped
int myResult = (numberToLeftShift << positionsToShift) | existingNumber;
答案 1 :(得分:1)
根据您的文字说明,您应该使用
var myResult = (numberToLeftShift << positionsToShift) | existingNumber;