'Why this shift operation plus bitwise works only up to 31?
Why shift operation below works and end up equal? Is there any name for this pattern? I am trying to find out what was going on in the head of the person who wrote this code!
int i = 0x1;
i |= 0x1 << 1;
i |= 0x1 << 2;
i |= 0x1 << 3;
i |= 0x1 << 4;
i |= 0x1 << 5;
int j = 5;
if( ((0x1 << (j + 1)) - 1) == i)
{
// WHY?
}
I tried to check if this is true for all numbers but only works up to 31.
for (int i = 1; i <= 100; i++) {
int total_1 = 0x1;
for (int j = 1; j <= i; j++) {
total_1 |= 0x1 << j;
}
int total_2 = (0x1 << (i + 1)) - 1;
if (total_2 == total_1) {
} else {
cout << i << endl;
break;
}
}
UPDATE
Please explain the first part why they would end up equal?
Solution 1:[1]
UPDATE Please explain the first part why they would end up equal?
((0x1 << (j + 1)) - 1)
sets j
lower bits to 1
Example:
If j
is 3, j+1
is 4, 1
shifted by 4 is 0b1000
; subtract 1 - you get 0b0111
Re: Is there any name for this pattern?
- I looked here, this pattern is used a couple of times, but is not named. Probably, too obvious :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |