Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to convert from two's complement to sign-magnitude in C using only the operators

! ~ & ^ | + << >>

My approach is to find sign: int sign = !(!(a>>31));

basically, if sign == 1 . I want to flip the number and add 1 else just want to display the number.

The thing is I can't use any loops, if statements etc. This is what I'm working on:

int s_M = ((((a+1)>>31)^sign)+1)&sign;

any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
207 views
Welcome To Ask or Share your Answers For Others

1 Answer

From http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs

int const mask = v >> 31;
unsigned int r = (v + mask) ^ mask;

Gives the absolute value (magnitude). If you wish to add the sign bit back simply mask and or the 32nd bit:

unsigned int s_M = r | (v & 0x80000000);

Or if you're looking for a one liner:

unsigned int s_M = ((v + (v >> 31)) ^ (v >> 31)) | (v & 0x80000000);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...