jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes Shift operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Shift operators" Watch "Shift operators" New topic
Author

Shift operators

Niyas Ahmed Sheikh
Ranch Hand

Joined: Jun 15, 2005
Posts: 129
Hi,

I am start learning the Shift operator in Campfire. It is excellent and very simple to learn. I am always struggle with shift operators, however this article helps me lot to understand the concept.

I have one doubt in this regard:

Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

11111111111111111111111111010110 (-42)
11111111111111111111111111101011 (-42 >> 1)
11111111111111111111111111110101 (-42 >> 2)
11111111111111111111111111111010 (-42 >> 3)
11111111111111111111111111111101 (-42 >> 4)
11111111111111111111111111111110 (-42 >> 5)

The bits on the right side fall off into the bit bucket as they're shifted off. The >> retains the value of the sign bit.

Hope this helps.
[ September 01, 2005: Message edited by: Steve Morrow ]
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Negative numbers are stored in binary form as two's complement.

So -42 is: 11010110 (expressed as an 8-bit two's complement number)

When you shift the number right, the sign bit (the leftmost bit) will be extended, so -42 >> 5 gives you: 11111110, which is -2.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3419
    
  12
Originally posted by Niyas Ahmed Sheikh:
128 64 32 16 8 4 2 1
0 0 0 1 1 0 0 0

20 = 00011000


I think a refresher course in decimal maths might help first.

[ September 01, 2005: Message edited by: Joanne Neal ]

Joanne
 
Consider Paul's rocket mass heater.
 
subject: Shift operators
 
Similar Threads
Shift operators
Shift operator precedance
help ? in understanding
Help Me Out With Shift Operators...
Shift Operator