Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Significance of %x and ~

Tags:

c

printf

int m=32
printf("%x" , ~m);

Output of this statement is ffdf and without ~ output is 20. What is the significance of %x and ~?

like image 693
Brite Roy Avatar asked Jan 17 '12 19:01

Brite Roy


4 Answers

The ~ operator is bitwise negation. It will print bitwise negation of m's 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

And:

1101 1111 = 0xdf
like image 107
Pablo Santa Cruz Avatar answered Oct 16 '22 01:10

Pablo Santa Cruz


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
like image 31
Edward Thomson Avatar answered Oct 16 '22 01:10

Edward Thomson


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).

So,

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

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


[Sources]
http://en.wikipedia.org/wiki/Bitwise_operation#NOT
http://en.wikipedia.org/wiki/Hexadecimal
http://en.wikipedia.org/wiki/Printf_format_string

like image 2
Omar Avatar answered Oct 16 '22 01:10

Omar


And %x means you print the value of x in hexadecimale.

like image 1
delannoyk Avatar answered Oct 16 '22 00:10

delannoyk