I always subtract by 32768 when I have an unsigned short that I want to convert to a signed one.
Is that the fastest way to do it, or are there faster ways?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If the value is between from 0 to
SHRT_MAX(inclusive), there’s nothing to worry about and the cast ((short)) is optional (unless your compiler is paranoid or configured to be paranoid).If the
unsigned shortvalue can be greater thanSHRT_MAX, about the only legal way to convert it toshortis:This, of course, relies on signed shorts being 2’s complement with
SHRT_MIN= –SHRT_MAX– 1.A modern compiler will optimize away all the nonsense inside this function and just generate code to return
s.EDIT: Compiled the above with gcc 4.6.2 as
gcc -Wall ush2sh.c -O2 -S -o ush2sh.sto this assembly code: