*
The moose likes Beginning Java and the fly likes Bitwise operator left shifting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Bitwise operator left shifting " Watch "Bitwise operator left shifting " New topic
Author

Bitwise operator left shifting

Varshini Priya
Ranch Hand

Joined: Feb 17, 2008
Posts: 93

Hi all,

Im trying to execute the below program, im not able to understand the leftshifting functionality

public class shiftdemo
{
public static void main(String[] args)
{
System.out.println("14 in binary format is:");
System.out.println("1110 \n");
System.out.println("Now right shifting the bits by 2");
System.out.println("14>>2="+(14>>2));
System.out.println("now left shifting the bits by 2");
System.out.println("14<<2="+(14<<2));
}
}
Output

C:\PROGRA~1\Java\JDK15~1.0_0\bin>java shiftdemo
14 in binary format is:
0000 00000 0000 1110

Now right shifting the bits by 2
14>>2=3
now left shifting the bits by 2
14<<2=56

Im not clear how this left shifting works. Please help me understand this. Thanks
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3429
    
  12
If you start with
0000 00000 0000 1110
and shift all the bits right by two places you get
0000 00000 0000 0011 (the rightmost two bits are lost)
which is 3

If you start with
0000 00000 0000 1110
and shift all the bits left by two places you get
0000 00000 0011 1000 (the two empty bits on the right are filled with zero)
which is 56
[ November 21, 2008: Message edited by: Joanne Neal ]

Joanne
Olivier Legat
Ranch Hand

Joined: Nov 17, 2007
Posts: 176

yes what joanne says is write because each bit is worth 2^n where n is equal the bit's position from the right starting from 0.

so:
0000 00000 0000 1110 [Base-2] =
2^3 + 2^2 + 2^1 [Base-10] = 14

0000 00000 0000 0011 [Base-2] =
2^1 + 2^0 [Base-10] = 3

0000 00000 0011 1000 [Base-2] =
2^5 + 2^4 + 2^3 [Base-10] = 56

Just pointed that out in case you didn't know about binary numbers


Olly
Varshini Priya
Ranch Hand

Joined: Feb 17, 2008
Posts: 93

Thanks all for the detailed explanation
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38025
    
  22
Originally posted by Olivier Legat:
yes what joanne says is write because each bit is worth 2^n . . .


Except for the signed numbers (byte short int long) where the very first bit on the left is worth minus2^n.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38025
    
  22
And please find the code button and indent your code; it makes it much easier to read.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Bitwise operator left shifting
 
Similar Threads
How this output is coming regarding left shift operator
Shift operators !
Why is Integer.rotateLeft() implemented in this way?
i don't get shift operators!!!!
operators