0x01010101 如何等同于 1<<24 + 1<<16 + 1<<8 + 1

How 0x01010101 is equivalent to 1<<24 + 1<<16 + 1<<8 + 1

This question gives explanation about SWAR algorithm used for counting number of 1s in a given number. While explaining ilmari 写道 0x01010101 = (1 << 24) + (1 << 16) + (1 << 8) + 1。谁能解释一下它是如何相等的。

1 0000 0000 0000 0000 0000 0000  Shifting 1 left by 24 places
          1 0000 0000 0000 0000  Shifting 1 left by 16 places
                    1 0000 0000  Shifting 1 left by  8 places
                              1  
================================
1 0000 0001 0000 0001 0000 0001   Result after adding

即0x01010101.

让我们从总数开始:

Hex:     0x01010101
Decimal: 16843009
Binary:  1000000010000000100000001

现在逐一查看。从 1 << 24 开始(也就是 1 left shifted 24 次,也就是带有 24 个零的二进制 1):

Calculation: 1 << 24
Decimal: 16777216
Binary: 1000000000000000000000000
//      ^ 25th position because 1 was shifted 24 times to the left

Calculation: 1 << 16
Decimal: 65536
Binary: 0000000010000000000000000
//              ^ 17th position because 1 was shifted 16 times to the left

Calculation: 1 << 8
Decimal: 256
Binary: 0000000000000000100000000
//                      ^ 9th position because 1 was shifted 8 times to the left

1 很明显,所以我不会包括在内。现在将它们全部加在一起:

  1000000000000000000000000 = 1 << 24
  0000000010000000000000000 = 1 << 16
  0000000000000000100000000 = 1 << 8
+ 0000000000000000000000001 = 1
  |-------|-------|-------|
  1000000010000000100000001 = 16843009

然后我们回到开头,16843009 的十六进制是 0x01010101

您首先需要了解 << 运算符在做什么。它向左执行按位移位。让我们对二进制表示法采用 0b 前缀,对十六进制表示法采用 0x 前缀:

1 << 8 = 0b100000000 = 256 = 0x100

同样:

1 << 16 = 0b10000000000000000 = 65536 = 0x10000

所以:

(1 << 8) + (1 << 16) = 0x10100

通过添加 (1 << 24)1,您将得到最终结果:0x01010101.

请注意,虽然它看起来很像二进制值,但实际上是十六进制值。如果我们把它写成二进制,我们得到:

 0b1000000010000000100000001
   ^       ^       ^       ^
bit #24 bit #16  bit #8  bit #0