CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to support@ccsinfo.com

should a right-shift on a signed int16 do sign extension?

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
truevenik



Joined: 03 Feb 2004
Posts: 5

View user's profile Send private message

should a right-shift on a signed int16 do sign extension?
PostPosted: Wed Jun 16, 2004 12:14 pm     Reply with quote

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
Eric Minbiole



Joined: 10 Jun 2004
Posts: 16
Location: USA

View user's profile Send private message Visit poster's website

PostPosted: Wed Jun 16, 2004 12:35 pm     Reply with quote

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.
rnielsen



Joined: 23 Sep 2003
Posts: 852
Location: Utah

View user's profile Send private message

PostPosted: Wed Jun 16, 2004 12:38 pm     Reply with quote

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
Guest








PostPosted: Wed Jun 16, 2004 9:41 pm     Reply with quote

thanks guys - that clears it up.
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group