Win a copy of Rust Web Development this week in the Other Languages forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Tim Cooke
• Campbell Ritchie
• Ron McLeod
• Liutauras Vilda
• Jeanne Boyarsky
Sheriffs:
• Junilu Lacar
• Rob Spoor
• Paul Clapham
Saloon Keepers:
• Tim Holloway
• Tim Moores
• Jesse Silverman
• Stephan van Hulst
• Carey Brown
Bartenders:
• Al Hobbs
• Piet Souris
• Frits Walraven

# shift operator with negative numbers

Greenhorn
Posts: 1
• Number of slices to send:
Optional 'thank-you' note:
what is the complete procedure of for example:
-12>>3
and, 12>>>3
and, -12>>>2

Chicken Farmer ()
Posts: 1932
• Number of slices to send:
Optional 'thank-you' note:

Originally posted by talib kaimkhani:
what is the complete procedure of for example:
-12>>3

-12 is represented as 11111111 11111111 11111111 11110100

Since >> is a signed shift, you're basically going to move all the ones to the right 3 times, replacing the ones at the left end with more 1's (to keep the sign), and losing any 1 that falls off the right end. You end up with
11111111 11111111 11111111 11111110

and, 12>>>3

00000000 00000000 00000000 00001100
This is the unsigned bit, meaning that you still move the ones to the right 3 times, but you don't add ones to the left, you keep them zeroes. All you have to worry about is moving the 1's to the right 3 times. If the one falls off the end, it's gone, resulting in:
00000000 00000000 00000000 00000001

and, -12>>>2

11111111 11111111 11111111 11110100
Same thing as above, but remember, you're not replacing the ones at the left with more ones, they become zeroes. This causes the number to lose it's sign, and results in a relatively large number.
00111111 11111111 11111111 11111101

I'll let you figure out what the resulting numbers are for each, but that's what happens with the shifting
Hope that helps some
Jason

Greenhorn
Posts: 11
• Number of slices to send:
Optional 'thank-you' note:
This post prompted me to review how negative numbers are represented.
-1 is 11111111 11111111 11111111 11111111
Hence -12 is 11 less than this or -8 -2 -1 less:
11111111 11111111 11111111 11110100

Greenhorn
Posts: 6
• Number of slices to send:
Optional 'thank-you' note:
As for how to represent negative numbers it might be easier to rember like this: negate(invert transfortm 0 to 1 and 1 to 0) the positive number and add 1
Example :-12
+12 = 0000 0000 0000 1100
negate= 1111 1111 1111 0011
add 1 + 0000 0000 0000 0001
____________________________
-12 = 1111 1111 1111 0100

 I just had the craziest dream. This tiny ad was in it. Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton