(1 << j) - 1
is a number with j
one bits on the right
j bits
┌──────┐
00...0011...111
max
is a number with all one bits
11...1111...111
Each one bit from max
will become 0 when subtracting from the one bit from (1 << j) - 1
, and remain 1 otherwise. Hence max - ((1 << j) - 1)
will produce a value with j zero bits on the right
j...210 ← bit position
11...1111...11
- 00...0011...11
──────────────────
11...1100...00
That means the result is the bitwise not of (1 << j) - 1
, i.e.
max - ((1 << j) - 1) == ~((1 << j) - 1)
Is (1<<(j-1)) equivalent to ((1 << j) - 1)?
1 << (j-1)
shifts 1 j-1
places to the left and produces 2j - 1, so it has j-1
zeros on the right followed by a one 100...00
. (1 << j) - 1
gives a number with j
zeros on the right which is 2j - 1, as said above. Can you guess they're similar or not?