+ 1
Why is the output of int ch='aa'; cout<<ch; as 24929???? and similarly for ch='zz'; cout<<ch; as 31354??? please explain......
3 Answers
+ 3
Each character is stored in memory as a serie of 0s and 1s like anything else, and we refer to the corresponding binary number as the ascii number of that character. For example, 'a' is 97, 'b' is 98, ..., 'z' is 122, 'A' is 65, 'B' is 66, ..., 'Z' is 90, etc. (Look up an ascii table on the web for all the values). Characters are stored in 1 byte (so up to 2^8 = 256 different values).
"aa" is an array of characters of size 2 (which thus takes 2 bytes in memory since a single character takes 1 byte) with 'a' in each cell. The data in memory is thus 97 97, or in binary 01100001 01100001. You are then interpreting that as an integer number (2 bytes), which is 97*(2^8) + 97 = 97*256 + 97 = 24929.
Same deal for "zz" which is 122*256 + 122 = 31354.
Feel free to ask for more clarifications if you need.
(Funny thing, I didn't know Fabrizio already replied, and with a much more concise answer to boot.)
+ 2
'aa' is interpreted as a 2-bytes value, each byte equal to the ASCII value of 'a' (61 hex, 97decimal). So when we convert 'aa' into an integer we get (97*256)+97 = 24929
0
61 hex why did you multiply 97*256???.. Fabrizio?