Ron Eggler <
ronDOT...@tscheemail.com> wrote:
> I want to write a a function that takes an 8 bit number and calculates the
> 2's complement of it and returns a signed character.
> What I got so far:
> The problem i'm having is, that the multiplication *-1 gives me the wrong
> value, assuming i got 20 in num and then make a * -1, I get 236 and I can't
> figure out why... anyone?
236 (0xEC) is the 2's complement of 20 (0x14). Using the '~' ope-
rator and then adding 1 to the result should work everywhere,
for it to work by multiplying by -1 requires that your machine
uses 2's complement internally (but most do so nowadays, I guess).
> Code:
> char bintodec(unsigned char bin) {
> char num;
> num = bin;
> printf("0x%x -> 0x%x\n",bin,num);
> if (num & 0x80) {
> printf("bit 15 set 0x%x!\n",num);
> num = ~num;
> printf("0x%x\n",num);
> num++;
> printf("0x%x, %d\n",num,num);
> num = num*-1;
> printf("%d\n",num);
> return num;
> }
> printf("%d is >=0\n",num);
> return 0;
> }
From your code it's impossible to say what is going on - for 20 (and
eveything below 127) the function always returns 0. And, if you start
doing bit-diffling you should take care to clearly distinguish between
signed and unsigned variables, e.g. whhy is 'num' a char (which could
be a signed or unsigned, that depends on your architecture) when 'bin'
is an unsigned char? For bit-fiddling it's usually better to stick
to unsigned quantities,
Regards, Jens
--
\ Jens Thoms Toerring ___
j...@toerring.de
\__________________________
http://toerring.de