cylin wrote:
unsigned int ATwoSComplement = ( ~A + 1 ) & 0x003FFFFF;
Yes, that's simple.
But it seems that "( ~A + 1 ) & 0x003FFFFF" is always positive.
How can I handle if the 2's complement is negative?
It is bit 21 which tells you if the number should be output
as a negative one.
bit 21 set -> negative number. output '-' and the 2-s complement of the number
bit 21 not set -> positive number, just output it.
So in your case:
22 1111 1111 1100 0000 0000
10 9876 5432 1098 7654 3210
A= 11 1111 1111 1110 1100 0000 = 4193984
since bit 21 is set, A holds a negative number.
But which one:
11 1111 1111 1110 1100 0000 number
00 0000 0000 0001 0011 1111 1-compl
00 0000 0000 0001 0100 0000 2-compl = 256 + 64 = 320
so the bit pattern
11 1111 1111 1110 1100 0000
represents the number -320
The benefit of 2-s complement comes into play when doing
arithmetic. You just don't care if the number is positive
or negativ, you simply treat all numbers as beeing positive
and do the arithmetic (the sign bit will take care of itself).
It is only during input/output that an entered sign or bit 21 needs
attention.
Input: If the user enters a negative number, you read that
number as if it were a positive one (without the '-') and
do a 2-s complement on it to negate it.
Output: if bit 21 is set, you output a '-' since it is a negative
number, apply 2-s complement on the number (again: to negate it
and thus make it positive) and output that number.
Also note: with 22 bits, one bit for sign, you can't
represent 4193984. You simply don't have enough bits
for it.
Also note: you can't use your compilers facilities to output
negative numbers, since your compiler doesn't know that you
treat bit 21 as the sign bit. Thats why it is not meaningfull
in your case to talk about the number 4193984 although you
will see that number when you do a printf on A. But your
compiler doesn't know that bit 21 is the sign bit, thus ...
void OutputMyNumber( unsigned int A )
{
if( A & 0x002000000000 ) { // bit 21 set?
// if yes: negative number
printf( "-" );
A = ( ~A + 1 ) & 0x003FFFFF;
}
printf( "%d", A );
}
--
Karl Heinz Buchegger
kb******@gascad.at