For this assignment I can only use basic bitwise operators and no control structures, so I’ve come up with this code so far to convert sign-magnitude to two’s complement.
int sm2tc(int x) {
// Invert and add 1
// Problem: sm has 2 zeros.. 1000...000 & 0000...000
int tmin = 1 << 31;
int mask = x >> 31; // Determine sign of x
int mask2 = ~tmin; // Negate tmin to get 0111111...
int first = (x ^ mask) + (~mask + 1) ;
int second = first & mask2; // Turns of MSB
return second;
}
Where have I gone wrong?
So, what you really want to compute is
But of course you’re not allowed control structures. The first step is to rewrite
-(x & ~sign_bit)using just the+and^operators:(-1 ^ (x & ~sign_bit)) - -1. Now note that if(x & sign_bit)is zero then(0 ^ (x & ~sign_bit)) - 0is equal tox. We now haveYou then just need to replace the
-1and0with functions ofxthat generate those values depending on the sign bit, and lo and behold both sides of the condition become the same expression and the condition becomes unnecessary.