c – Significance of %x and ~

c – Significance of %x and ~

The ~ operator is bitwise negation. It will print bitwise negation of ms value. %x means that printf will output its value in hexadecimal format.

So, value 0xffdf is the negation of value 0x20 (32).

Value 32 (int bits would be):

0000 0000 0010 0000

Its bitwise negation will be:

1111 1111 1101 1111

Which makes sense since:

1111 1111 = 0xff


1101 1111 = 0xdf

The %x is the printf format that indicates that the int value should be displayed in hexadecimal.

The ~ is bitwise NOT, which flips all the bits in the integer.

The statement:

printf(%x, m);

will display the output 20 as 0x20 = decimal 32.

The statement:

printf(%x, ~m);

will display the output ffdf as 0xffdf is the bitwise inverse of 0x20.

It may make more sense to visualize the bitwise negation in binary:

Base 10:         32                  65503
Base 16:        0x20                0xFFDF
Base 2:    0000000000100000    1111111111011111

c – Significance of %x and ~

The ~ symbol represents the bitwise NOT, or complement operator; a unary operation that performs logical negation on each bit, forming the ones complement of the given binary value. Binary digits that are 0 become 1, and those that are 1 become 0.

32 is 00100000 in binary, and ~32 is 11011111 in binary (or 223 in decimal).

The %x option in the printf function will display a unsigned hexadecimal format (using lowercase letters).


printf(%x, m); // displays the hexadecimal value of 32 (00100000), 20

printf(%x, ~m); // displays the hexadecimal value of ~32 (11101111), ffdf


Leave a Reply

Your email address will not be published.