This question gives explanation about SWAR algorithm used for counting number of 1s in a given number. While explaining ilmari wrote 0x01010101 = (1 << 24) + (1 << 16) + (1 << 8) + 1. Can someone explain how it is equal.
You'll first need to understand what the <<
operator is doing. It performs a bitwise shift to the left. Let's adopt the 0b
prefix for binary notation and 0x
for hexadecimal notation:
1 << 8 = 0b100000000 = 256 = 0x100
Similarly:
1 << 16 = 0b10000000000000000 = 65536 = 0x10000
So:
(1 << 8) + (1 << 16) = 0x10100
By adding (1 << 24)
and 1
, you'll get the final result: 0x01010101
.
Please note that while it looks an awful lot like a binary value, it is a hexadecimal one. If we write it as binary, we get:
0b1000000010000000100000001
^ ^ ^ ^
bit #24 bit #16 bit #8 bit #0