Bitwise Operation

  • Thread starter Pasquale Imbemba
  • Start date
P

Pasquale Imbemba

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
 
T

Thomas Weidenfeller

Pasquale said:
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 :)
 
R

Roedy Green

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
and chase links.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top