Convert two's complement to sign-magnitude

前端 未结 4 1311
伪装坚强ぢ
伪装坚强ぢ 2020-12-22 10:35

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

! ~ & ^ | + << >>

My approach is t

4条回答
  •  臣服心动
    2020-12-22 11:23

    I'm not entirely sure what the output should be, but to obtain the magnitude you can do something like this:

    int m = (a^(a>>31)) + sign;
    

    Basically, shifting a negative number 31 bits to the right will make it all 1's, or 0xffffffff, which you can then use to xor the input number and make it positive. As you correctly noted sign needs to be added then for the correct result in that case.

    If the input number was positive to begin with, the shift results in a zero and so the xor does nothing. Adding sign in that case also doesn't do anything, so it results in the input number.

提交回复
热议问题