Character Print on the Terminal

char x = '0';

cout << "(~0 ): " <<~x << endl;
cout << "~(~0 ): " <<~(~x ) << endl;
cout << "(0 << 4 ): " <<(x << 4 ) << endl;
cout << "(~0 << 4 ): " <<(~x << 4 ) << endl;
cout << "~(0 << 4 ): " <<~(x << 4 ) << endl;
cout << "~(~0 << 4 ): " <<~(~x << 4 ) << endl;

RESULT:

(~0 ): -49
~(~0 ): 48
(0 << 4 ): 768
(~0 << 4 ): -784
~(0 << 4 ): -769
~(~0 << 4 ): 783


Can anybody please explain what is the logice, or put a tutorial URL on this matter
These are all bitwise operations. A char is normally a signed 8 bit variable. So, what you are doing is getting the value of '0', 48, 0x30 or 0011 0000 (ascii, decimal, hexadecimal and binary respectively). Then, you can follow the bit shifting to work out the value. Note that because its signed, the first bit is either 0 (for positive) or 1 (for negative), and doesn't take part in the actual value of the number.

EDIT: Also, note that the shifts seem to be making the number an int (or anything larger than 8-bits in size), because it has gone larger than the maximum value for a signed char (127).
Last edited on
May be useful, bitwise operators tutorial;
http://www.cprogramming.com/tutorial/bitwise_operators.html
Topic archived. No new replies allowed.