if(a<0)
a = -((-a)>>1));
else
a = a>>1;
Binary shift of signed vs unsigned types
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:
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
Cheers
Brad
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
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement