Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left bit shift 0 in Java

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?

like image 586
Riz Avatar asked Dec 02 '22 18:12

Riz


1 Answers

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;
like image 163
Mike Christensen Avatar answered Dec 15 '22 14:12

Mike Christensen