Velocity Reviews > Java > Bitwise Operation

# Bitwise Operation

Pasquale Imbemba
Guest
Posts: n/a

 05-06-2004
Hello,

in my little programm:

public class Shift1 {
public static void main (String [] args) {

int thirteen = 13;
int ten;

ten = thirteen << 1;

System.out.println ( thirteen + " is now " + ten);
}
}

I expect 13 (1101) to be shifted by one position to the left, i.e.
becoming 101. I expected Java to fill the righthand of the bit sequence
with a 0, thus 1010, which should return me 10. It returns 6 instead.
What I wrong here?

Bye
Pasquale

--
=======
"I'd like to buy Windows." "Are you mad?" "Why, is this part of the
=======

Thomas Weidenfeller
Guest
Posts: n/a

 05-06-2004
Pasquale Imbemba wrote:
> Hello,
>
> in my little programm:

For beginner's questions, please consider comp.lang.java.help. F'up set.

> I expect 13 (1101) to be shifted by one position to the left, i.e.
> becoming 101.

No, it becomes 26 (11010). As you wrote, shifted one position to the left.

> I expected Java to fill the righthand of the bit sequence
> with a 0,

Yes, see above.

> thus 1010,

No, Java ints have space for 32 bits (31 plus one sign bit). The bit
will drop of when you have reached that limit, not before. (you will see
some strange results right before, when your bit hits the sign bit
position. Your number will then suddenly presented as a negative number,
but that's another issue).

> which should return me 10. It returns 6 instead.

I bet it returns 26, which is the correct answer.

> What I wrong here?

Your understanding of integer types and bit shifting in Java.

To get your result you need to mask out the bits you want, effectively
choping of the bits you don't want.

ten = (thirteen << 1) & 0xF;
/Thomas

PS: Couldn't resist: Old programmer "joke": There are 10 types of people
in the world. Those who understand binary, and those who don't

Roedy Green
Guest
Posts: n/a

 05-06-2004
On Thu, 06 May 2004 10:21:14 GMT, Pasquale Imbemba
<(E-Mail Removed)> wrote or quoted :

> int thirteen = 13;
> int ten;
>
> ten = thirteen << 1;
>
> System.out.println ( thirteen + " is now " + ten);
> }
>}
>
>I expect 13 (1101) to be shifted by one position to the left, i.e.
>becoming 101. I expected Java to fill the righthand of the bit sequence
>with a 0, thus 1010, which should return me 10. It returns 6 instead.
>What I wrong here?

That is a LEFT shift, equivalent to multiplying by 2.
thirteen is 1101 -> shifted left, with a 0 or the right is 11010
which is 26.

If you did a RIGHT shift:

x = thirteen >> 1;
you would get 1101 -> 110 with a 0 sign bit coming in the high end.

Think of the little arrows pointing which way the bits are moving.

see http://mindprod.com/jgloss/operator.html

--
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.