Eamorr
Eamorr

Reputation: 10012

Masking a bit in C returning unexpected result

0x7F000000 is 0111 1111 0000 0000 0000 0000 0000 0000 in 32 bit binary.
0x01000058 is 0000 0001 0000 0000 0000 0000 0101 1000.

When I AND the two numbers together I expect 0000 0001 0000 0000 0000 0000 0000 0000, but for some reason I get 0.

Here is my code:

#define MASK_binop     0x80000000
#define MASK_operation 0x7F000000

int instruction=atoi(line);
if((MASK_binop & instruction)>0)
    printf("binop\n");
else if((MASK_operation & instruction)>0)
    printf("operation\n");

Each of the above comparisons keeps returning zero. Is it something to do with 32/64 bits? I'm using 64-bit compiler.

Upvotes: 2

Views: 463

Answers (3)

Daniel Evans
Daniel Evans

Reputation: 6808

Do

printf("%x", instruction);

and ensure that instruction is really what you expect it to be.

you can also do:

printf("%x", MASK_binop & instruction);
printf("%x", MASK_operation & instruction);

To see what exactly is happening.

Upvotes: 3

taskinoor
taskinoor

Reputation: 46027

If line contains "0x01000058" then atoi will return 0 as atoi works with decimal representation, not hex 0x representation. And then the AND obviously is zero. Try to printf the value of instruction.

Upvotes: 4

Mark Wilkins
Mark Wilkins

Reputation: 41232

I just tried it and it appears to work as expected. Do a printf( "%x\n", instruction); to show what the value is.

Upvotes: 1

Related Questions