Archived

This topic is now archived and is closed to further replies.

Binary shift of signed vs unsigned types

This topic is 6014 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If I have a signed type, can I do binary shift ops on it? I haven''t tried it, it seems to me since negative numbers are stored using two''s complement, that it would screw everything up. Assuming I have a signed char, equal to -4. The binary representation is 11111100 (I think). If I right shifted that by 1 (hoping to divide by 2) I think I''d get 01111110, which is 126, not -2. Or do binary shifts take into account signed vs unsigned types, so we don''t have to worry about that? Otherwise, we''d have to do something like this:
  

if(a<0)
    a = -((-a)>>1));
else
    a = a>>1;

  

Share this post


Link to post
Share on other sites
Most (I''d say all but I might be lying) know that when you go -4 >> 1 you get -2. I''m guessing but I assume that the compiler looks at the type, if it is unsigned then the most significant bits are padded with 0''s. If the type is signed then on a >> the value of the left most bit before shifting is value that is put into the new highest bit (ie if it was a 1 before it will still be a 1 after shifting) I''ve done a quick test with MSVC++ and it follows this behaviour. Incidentally I imaging that the compiler would need to be smart about << when the uppermost bit is about to be overwritten, so you don''t go from a +ve number to a -ve number.

Cheers
Brad

Share this post


Link to post
Share on other sites
quote:
Original post by Vanukoff
If I have a signed type, can I do binary shift ops on it?


Why, yes, you can.

quote:

I haven''t tried it,


Most people appreciate trying things yourself before you post simple questions to the board, just a future tip.

quote:

Assuming I have a signed char, equal to -4. The binary representation is 11111100 (I think). If I right shifted that by 1 (hoping to divide by 2) I think I''d get 01111110, which is 126, not -2.


If you declare a integer as signed, and it has a bit set in the leftmost location, it will keep that bit set period on a right shift, so -4 (11111100) shifted right would be -2 (11111110). If it is unsigned, the leftmost position will always be zero.


Mike

Share this post


Link to post
Share on other sites

Thanks for the replies. Very helpful.

...Normally I would test it out on my own, but I''m at work right now (not a programming job :< ) and the thought just popped into my head during a break. I figured if someone wanted to test it for me, it was their choice, I didn''t force anyone to I was just polling for a quick answer...

Thanks again.

Share this post


Link to post
Share on other sites