• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Shift operators

 
Niyas Ahmed Sheikh
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15441
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic