转换补签署震级 [英] Convert two's complement to sign-magnitude
本文介绍了转换补签署震级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只使用运营商需要从两个的补转换为符号 - 幅度用C
I need to convert from two's complement to sign-magnitude in C using only the operators
! ~ & ^ | + << >>
我的办法是找迹象: INT标志!=((A&GT;!&GT; 31));
基本上,如果标志== 1
。我想翻转号并添加1别的只是想显示的号码。
basically, if sign == 1
. I want to flip the number and add 1 else just want to display the number.
问题是我不能使用任何循环,if语句等。
这就是我工作的:
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;
有什么建议?
推荐答案
HTTP: //graphics.stanford.edu/~seander/bithacks.html#IntegerAbs
int const mask = v >> 31;
unsigned int r = (v + mask) ^ mask;
给出的绝对值(幅度)。如果您要添加的符号位后面简单地掩盖和或第32位:
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);
这篇关于转换补签署震级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文