Converting from sign-magnitude to two's complement
For this assignment I can only use basic bitwise o开发者_如何学JAVAperators 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
result = (x & sign_bit) ? -(x & ~sign_bit) : x;
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)) - 0
is equal to x
. We now have
result = (x & sign_bit) ? (-1 ^ (x & ~sign_bit)) - -1 : (0 ^ (x & ~sign_bit)) - 0
You then just need to replace the -1
and 0
with functions of x
that 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.
精彩评论