C Bit Manipulation Problem

Associate
Joined
1 Mar 2010
Posts
1,389
When I perform the calculation 25441 & 0000000011111111 the answer I recieve is puzzling. Instead of the expected 97 I instead get 577.

Code:
printf( "%d", 25441 & MASK );

The output is 577 where MASK is 0000000011111111.

I performed the bitwise addition manually to double check and the answer should definitely be 97. I must have an error somewhere.

Any help is much appreciated.
 
It's because you are mixing number bases. You are using decimal and you are wanting MASK to be in binary.

0000000011111111 base 10 = 11111111 base 10
0000000011111111 base 2 = 255 base 10

25441 AND 11111111 = 577
25441 AND 255 = 97

Does that make sense?

Try using hex as well, #define MASK 0xFF

Maybe it would help if you wrote a function to translate between bases.
 
Back
Top Bottom