bit inversion and type size?

S

Samuel Stearley

I have a question about the ~ operator in C. In some code I compare
an eight bit value to an inverted 8 bit value, but when I run they are
never equal. So I disassembled the code and saw that the inversion is
a 32 bit operation, followed by a 32 bit compare.

So is my code wrong or is this a compiler bug? I'm using gcc 3.3.2

eg

typedef struct blob
{
UINT8 x;
UINT8 y;
}BLOB;

BLOB temp;

if (temp.x == ~temp.y)
{
/* snip */
}

resulted in the following powerpc assembly:

3e7c8: 89 21 00 11 lbz r9,17(r1) /* get byte y and clear upper 24
bits */
3e7cc: 3c 60 05 15 lis r3,1301
3e7d0: 88 01 00 10 lbz r0,16(r1) /* get byte x and clear upper 24
bits */
3e7d4: 60 63 01 01 ori r3,r3,257
3e7d8: 7d 29 48 f8 not r9,r9 /* 32 bit inversion, upper bits
are now set */
3e7dc: 7f 80 48 00 cmpw cr7,r0,r9 /* 32 bit compare */
 
S

Seebs

I have a question about the ~ operator in C. In some code I compare
an eight bit value to an inverted 8 bit value, but when I run they are
never equal. So I disassembled the code and saw that the inversion is
a 32 bit operation, followed by a 32 bit compare.
Yup.

So is my code wrong or is this a compiler bug? I'm using gcc 3.3.2

Your code's wrong. All values promote to int or larger when used in
an expression, so if you have an unsigned char x with the value 0x1, ~x
is ~(int) x. So on a 32 bit machine, it's 0xfffffffe, not 0xfe.
if (temp.x == ~temp.y)

Try
if (temp.x == (unsigned char) ~temp.y)

or possibly
if (temp.x == (~temp.y) & 0xff)
or something similar. (You'd want to define that mask in a nice clean
way, of course.)

-s
 
S

Samuel Stearley

Thanks.
Next question: are there any compiler flags or static analyzers that
can flag this with a warning ?

-Samuel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,072
Latest member
trafficcone

Latest Threads

Top