View previous topic :: View next topic |
Author |
Message |
truevenik
Joined: 03 Feb 2004 Posts: 5
|
should a right-shift on a signed int16 do sign extension? |
Posted: Wed Jun 16, 2004 12:14 pm |
|
|
Hi the following code doesn't do sign extension. Am I missing something or is the compiler missing something?
signed int16 result = -25152;
result >>= 4;
When I replace result >>=4; with result = result/16; it starts doing what I want...
Thanks
-Ben |
|
![](templates/subSilver/images/spacer.gif) |
Eric Minbiole
Joined: 10 Jun 2004 Posts: 16 Location: USA
|
|
Posted: Wed Jun 16, 2004 12:35 pm |
|
|
According to ISO/ANSI C, when shifting signed numbers it's up to the compiler to decide whether to do sign extension, or to just shift in 0's. CCS likely chose the simpler '0' approach to keep code size to a minimum.
You might be able to do something like
Code: |
if (result < 0)
{
result = -result;
result >>= 4;
result = -result;
}
|
I haven't tried it, but it seems like it still might be faster than a divide. |
|
![](templates/subSilver/images/spacer.gif) |
rnielsen
Joined: 23 Sep 2003 Posts: 852 Location: Utah
|
|
Posted: Wed Jun 16, 2004 12:38 pm |
|
|
When you do a shift >> ALL of the bits will be moved and zero's will be put in their place. This includes the sign bit. It will be moved four places and a zero will be in it's original place. This will have a drastic effect on your variable's value. Hence, -25152 (1001110111000000) if shifted four places will be 2524 (0000100111011100). You can't simply shift bits to get a divide-by result. You need to remember that each bit doubles the last bit's value (1, 2, 4, 8, 16, 32, 64....).
Ronald |
|
![](templates/subSilver/images/spacer.gif) |
Guest
|
|
Posted: Wed Jun 16, 2004 9:41 pm |
|
|
thanks guys - that clears it up. |
|
![](templates/subSilver/images/spacer.gif) |
|