Riz
Riz

Reputation: 6686

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?

Upvotes: 5

Views: 13096

Answers (3)

nashuald
nashuald

Reputation: 825

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

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

Upvotes: 4

Mike Christensen
Mike Christensen

Reputation: 91724

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;

Upvotes: 13

William Morrison
William Morrison

Reputation: 11006

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.

Upvotes: 2

Related Questions