清除 i 为 0 位
Clear i to 0 bits
我正在完成 Cracking the Coding Interview,其中一种位操作技术如下:
To clear all bits from i through 0 (inclusive), we take a sequence of all 1s (which is -1) and shift it left by i + 1 bits. This gives us a sequence of 1s (in the most significant bits) followed by i 0 bits.
int clearBitsIthrough0(int num, int i){
int mask = (-1 << (i + 1));
return num & mask;
}
-1 怎么是全 1 的序列?
假设您使用的是C/C++,int
表示一个带符号的32位整数,用two's complement表示。
-1
本身被假定为 int
类型,因此等同于 0xFFFFFFFF
。推导如下:
1
是 0x00000001
。将位取反得到 0xFFFFFFFE
,加一得到 -1
的二进制补码表示:0xFFFFFFFF
,一个 32 个 1 的序列。
我正在完成 Cracking the Coding Interview,其中一种位操作技术如下:
To clear all bits from i through 0 (inclusive), we take a sequence of all 1s (which is -1) and shift it left by i + 1 bits. This gives us a sequence of 1s (in the most significant bits) followed by i 0 bits.
int clearBitsIthrough0(int num, int i){
int mask = (-1 << (i + 1));
return num & mask;
}
-1 怎么是全 1 的序列?
假设您使用的是C/C++,int
表示一个带符号的32位整数,用two's complement表示。
-1
本身被假定为 int
类型,因此等同于 0xFFFFFFFF
。推导如下:
1
是 0x00000001
。将位取反得到 0xFFFFFFFE
,加一得到 -1
的二进制补码表示:0xFFFFFFFF
,一个 32 个 1 的序列。