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

前端 未结 5 1484
有刺的猬
有刺的猬 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:09

    To convert from Sign Magnitude x to Two's Complement y:

    1) On a two's complement machine.
    2) Use only !,~,|,&,^,+,>>,<<
    3) Does not use ?:, -, *, /
    4) Does not assume 4-byte int
    5) Work with all Sign Magnitude including +0 and -0

    #include 
    int sm2tc(int x) {
      int sign = x & INT_MIN;
      int negmask = UINT_MAX + !sign;
      return (x & ~negmask) | (negmask & ((~x + 1)^INT_MIN));
    }
    

提交回复
热议问题