Convert two's complement to sign-magnitude

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

    To get the last bit you could use mask operation

       int last_bit = 32 bit integer & 0x80000000 
       o/p  may be 0 or 0x80000000    
    

    if it is 0 just display the given number else you have to perform the following operations to represent in signed magnitude

    1) Subtract 1 from the number

    2) perform 1s complement on the resultant ( that is negation ~)

    3) Set the last bit of the resultant number

     I mean  ( ~ (num -`1) ) | 0x7fffffff 
    

    since your restricted not to use - operator. Perform the 2's complement on -1 and add it to the num.

    To put it simple in one line
     num & 0x80000000 ? printf("%d",(~(num+((~1)+1))) | 0x7fffffff) : printf("%d",num)   ;
    

提交回复
热议问题