Convert two's complement to sign-magnitude

前端 未结 4 1312
伪装坚强ぢ
伪装坚强ぢ 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:14

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

提交回复
热议问题