-
Bitwise operation
I tried the following program. Hex value works allright, but the decimal value gives me some negative numbers. What do do. Please any help. Thanks in advance.
Code:
#include <stdio.h>
void main(void)
{
unsigned x, y;
x=0x00f0;
y=~x;
printf("Hex=%x\n", y);
printf("Decimal=%d", y);
}
-
Don't lie to printf: tell it that the number you're printing is unsigned using the proper format specifier (specifically, %u).
-
Use %u to print an unsigned int. Also main() returns int, not void, and you should put an explicit "return 0;" at the end of main().
-
Taking the 1's complement of 0x00f0 yields 0xff0f. (Or, in the case of a 4 byte int, 0xffffff0f)
With the leftmost bit being on, and the int being defined as signed by default, you'll get a negative number.
Todd
-
thank you very much. %u works.