strange behaviour.......

• 05-01-2004
surdy
strange behaviour.......
i had to test whether sum of lower 4 bits of an 8-bit number(unsigned char) and that of two's complement of lower 4 bits of another 8bit numer(again unsigned char but this time i have a pointer to this no.) is greater than or equal to 16(10000)
i'll explain in detail if not clear
first of all two's complement of a no. is its one's complement+1
e.g. two's complement of 1001 = 0110(one's complement)+1=0111
similarly two's complement of 0001=1110+1=1111

now what i want to test
e.g. i have two numbers(binary) 00101000 00100011

lower four bits of 1'st number = 1000
two's compl. of lower four bits of 222nd no.(1100+1) = 1101
-------
Sum of the two =10101 =21(decimal)>16

now the code i used

if(a&15+(15-*ptemp&15)+1>=16)
printf("yes");
else
printf("no");

here a is unsigned int
ptemp is pointer to unsigned int

the logic used is lower 4 bits obtained by ANDing with 15(binary 1111) for a and *ptemp
1's complement of second number's lower 4bits obtained by subtrating them from 15(1111)
2's complement obtained by adding 1 to it

now my problem is
that the code gives correct result for some test values while incorrect for some other test values

Where is the mistake in my logic
compiler used turba c++ ver.3.0(borland international)

• 05-01-2004
zuiplap
so you would like to add "a&15" to (15-*ptemp&15)+1..

& has a lower priorty than + so you should use

(a & 15) + ((15 - *ptemp & 15) + 1) >= 16

which should work.. (i think)

a&15+(15-*ptemp&15)+1
is
a & (15 + ((15 - *ptemp)&15)+1)

so as you can see, this is wrong..

i hope this helps..
• 05-01-2004
surdy
oops!! i messed it up
thanx for pointing out the mistake
i think now this should work