即将完成一项任务,在最后一个问题上,我试图这样做,但我不知道我是否正确使用了位移。
对于这个问题,我必须提取整数的正确字节,然后得到该右字节的前3位,后3位和后2位,并将其分配给无符号整数变量。
到目前为止我尝试过的是:
int rightmost = (y>>24)&0xFF // to get rightmost byte
int first = (rightmost <<< 1)&0xFF // to get first 3 bits of that byte
int second = (rightmost >>> 3)&0xFF // to get next 3 bits
int third = (rightmost >>> 6)&0xFF // to get last 2 bits
我想知道我是否朝着正确的方向前进
我这样做:
var firstByte = y & 0xff;
这是最不重要的字节。如果y
中的值是12
,则所有位都将在该字节中。
然后,为了隔离该字节的各个部分,你必须使用&
来切断你不想要的所有位,然后使用>>
将这些位置到最不重要的位置。你这样做的顺序并不重要,尽管它确实决定你在&
的另一边放了什么:
var first3 = firstByte & 0x07; // no need to shift
var second3 = (firstByte >> 3) & 0x07; // shift by 3 and then mask off the rest
var last2 = (firstByte >> 6) & 0x03; // shift by 6 and mask
在二进制中,0x07
看起来像00000111
。因此,使用&
隔离数字中最不重要的3位。
测试如下。
JavaScript有点奇怪,因为在所有这些操作之间,语言将数字保持为64位浮点值。对于整数值,然而这并不重要,实际上优化的运行时实际上可能不会保持浮点表示,如果它真的很聪明。
var y = 2359; // binary: 100100110111
var firstByte = y & 0xff;
console.log("firstByte: " + firstByte);
var first3 = firstByte & 0x07;
console.log("should be 7: " + first3); // should be 7
var second3 = (firstByte >> 3) & 0x07;
console.log("should be 6: " + second3); // should be 6
var last2 = (firstByte >> 6) & 0x03;
console.log("should be 0: " + last2); // should be 0