Left bit shift 0 in Java

12,157

Solution 1

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;

Solution 2

You are using the operator << in a wrong way. It must to be:

int a = 0;
a |= a << 1;
System.out.println(a);

Solution 3

You are left shifting the literal 1 by the variable a. The value of variable a is zero. 1<<0 = 1

So you've just got your variables flipped. Try reversing the variables.

Share:
12,157
Riz
Author by

Riz

Updated on June 04, 2022

Comments

  • Riz
    Riz almost 2 years

    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?