位掩码和选择偶数位
Bitmask and selecting even bits
我正在读一本书,上面写着:
To select all the even bits in a 32 bit unsigned int, we can AND the
number with the bitmask 0xAAAAAAAAAA, which is a 32 bit number with
even bits set (0xA is a decimal 10, 1010 binary). For selecting odd
bits we can AND with bitmask 0x5555555555, which is a number with all
even bits set (0x5 is decimal 5, 0101 in binary)
我不明白 0x 或 1010 如何将所有偶数位设置为 1。如果您从右到左从零开始,显然是设置了奇数位。我错过了什么?
您需要从右开始 (LSB) 计算位的位置,作为第一位(奇数)和第二位(偶数)。
从左到右是你出错的地方。
看看实际操作时会发生什么:
二进制 32 位:
your number: 1111 1111 1111 1111 1111 1111 1111 1111
Mask: 1010 1010 1010 1010 1010 1010 1010 1010
result: 1010 1010 1010 1010 1010 1010 1010 1010
第一位(从右起!!!)是奇数,在使用 AND
运算符使用 0xAAAAAAAAAA
作为位掩码时不会被设置。只有偶数位会被设置。始终从最低有效位开始。
我正在读一本书,上面写着:
To select all the even bits in a 32 bit unsigned int, we can AND the number with the bitmask 0xAAAAAAAAAA, which is a 32 bit number with even bits set (0xA is a decimal 10, 1010 binary). For selecting odd bits we can AND with bitmask 0x5555555555, which is a number with all even bits set (0x5 is decimal 5, 0101 in binary)
我不明白 0x 或 1010 如何将所有偶数位设置为 1。如果您从右到左从零开始,显然是设置了奇数位。我错过了什么?
您需要从右开始 (LSB) 计算位的位置,作为第一位(奇数)和第二位(偶数)。
从左到右是你出错的地方。
看看实际操作时会发生什么:
二进制 32 位:
your number: 1111 1111 1111 1111 1111 1111 1111 1111
Mask: 1010 1010 1010 1010 1010 1010 1010 1010
result: 1010 1010 1010 1010 1010 1010 1010 1010
第一位(从右起!!!)是奇数,在使用 AND
运算符使用 0xAAAAAAAAAA
作为位掩码时不会被设置。只有偶数位会被设置。始终从最低有效位开始。