Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

shift operators

 
khella smith
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
is the <<(left shift)signed or unsigned? i was doing some revision in javacaps and it said that the left shift is signed and in R&H it does not specify and i assumed it was signed.could it be considered unsigned because it inserts zeroes in new positions like the >>>(un-signed right shift)?
pls tell me
..............
khella smith
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no difference between a signed and an unsigned left shift, that's why there is only one left shift operator.
In 8-bit terms: take a low(ish), positive number to start with
64 << 1 = 01000000 << 1 = 10000000 = 128
So that's how normal unsigned left shifts work. Now consider an unsigned, large number:
192 << 1 = 11000000 << 1 = 10000000 = 384 % 256 = 128 (Overflow)
It still worked, even though the result did no longer fit inside an 8-bit number. The same bit pattern in signed guise:
-64 << 1 = 11000000 << 1 = 10000000 = -128
This is exactly the right result.
So you can see that left-shift works by shifting in zeroes from the right, on both signed and unsigned numbers.
HTH
- Peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic