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.
How 0x01010101 is equivalent to 1<<24 + 1<<16 + 1<<8 + 1
2.9k Views Asked by sac At
3
There are 3 best solutions below
0

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
I.e. 0x01010101.
0

Let's start with the total number:
Hex: 0x01010101
Decimal: 16843009
Binary: 1000000010000000100000001
Now look at them individually. Start with 1 << 24
(aka. 1 left shifted 24 times, aka. a binary 1 with 24 zeroes):
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 is obvious, so I won't include that. Now add them all together:
1000000000000000000000000 = 1 << 24
0000000010000000000000000 = 1 << 16
0000000000000000100000000 = 1 << 8
+ 0000000000000000000000001 = 1
|-------|-------|-------|
1000000010000000100000001 = 16843009
And then we're back at the start, 16843009
in hex is 0x01010101
.
You'll first need to understand what the
<<
operator is doing. It performs a bitwise shift to the left. Let's adopt the0b
prefix for binary notation and0x
for hexadecimal notation:Similarly:
So:
By adding
(1 << 24)
and1
, 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: