Consider:
int a = 0;
a |= 1 << a;
System.out.println(a);
It prints "1". Why? I thought left bit shifting 0 by any number of times was still 0. Where's it pulling the 1 from?
The expression 1 << a;
will shift the value 1
, a
number of times.
In other words, you have the value 1:
0000001
Now, you shift the whole thing over 0 bits to the left. You then have:
0000001
You then have:
a |= 1 << a;
Which resolves to:
a = 0000000 | 0000001
Or:
a = 1;
You might have the operands mixed up. If you're trying to shift the value 0 one bit to the left, you'd want:
a |= a << 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With