Search code examples
javabitwise-operatorsbit-shift

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?


Solution

  • 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;