Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

c - Convert two's complement to sign-magnitude

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

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

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...