How to convert from sign-magnitude to two's complement

前端 未结 5 1424
有刺的猬
有刺的猬 2021-01-24 06:39

How would I convert from sign-magnitude to two\'s complement. I don\'t know where to start. Any help would be appreciated. I can only use the following operations:!,~,|,&,^,

5条回答
  •  暖寄归人
    2021-01-24 07:08

    You can convert signed-magnitude to two's complement by subtracting the number from 0x80000000 if the number is negative. This will work for a 32-bit integer on a machine using two's complement to represent negative values, but if the value is positive this will result in a two's complement negation. A right shift of a two's complement negative number will shift in one's, we can utilize this to make a mask to select between the original value, or the conversion of a signed-magnitude negative value to a two's complement negative value.

    int sm2tc(int x) {
      int m = x >> 31;
      return (~m & x) | (((x & 0x80000000) - x) & m);
    }
    

提交回复
热议问题