first, 97 * 101
is 9797
. (In hex, 0x2645
).
and char
is 1byte. so 0x2645
become 0x45
.
0x45 == 69 == 'E'
. That's it.
Question
Recently my C professor gave us the following puzzle:
char c1, c2, c3;
c1 = 'a';
c2 = 'e';
c3 = c1 * c2;
printf("%c",c3);
Answer: E
However, I'm a bit confused as to how this would be solved intuitively other than having the product already memorized. From what I've researched the int values of the characters 'a' and 'b' are 97 and 101 respectively and 'E' being 69 which is what I'm having a rough time understanding how that result was achieved.
Solution
first, 97 * 101
is 9797
. (In hex, 0x2645
).
and char
is 1byte. so 0x2645
become 0x45
.
0x45 == 69 == 'E'
. That's it.
OTHER TIPS
char c1, c2, c3;
c1 = 'a';
c2 = 'e';
c3 = c1 * c2;
The result is implementation-defined, but likely to be 'E'
.
The C language does not specify the numeric values of the characters 'a'
, 'e'
, and 'E'
(or of any character other than the null character '\0'
). For a system that uses an ASCII-based character set, the values are 97
, 101
, and 69
, respectively, but on a system that uses EBCDIC the values will be quite different.
Assuming an ASCII-compatible character set, the values of c1
and c2
will be promoted to int
before the multiplication. The result of the multiplication is 9797
decimal, or 0x2645
in hex.
The assignment converts that result from int
to char
. If char
is a signed type (as it commonly is), the result of the conversion is implementation-defined, but it's typically done by discarding all but the low-order bits. If char
is an unsigned type, the conversion is well defined, and is reduced modulo CHAR_BIT + 1
(very likely to be module 256).
The value assigned to c3
is probably going to be 0x45
, or 69
in decimal, or 'E'
as a character (again assuming an ASCII-compatible character set).
So the output is E
if a number of assumptions are satisfied:
char
is unsigned, or it's signed and the conversion from int
to char
discards the high-order bits; andCHAR_BIT == 8
And finally:
char
values, stores the product back in a char
object, and prints the result. Such code may be useful for testing your understanding of C, but it has no practical use (something that's true of a lot of class exercises).$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
97 * 101
9797
9797 % 256
69
quit
char
is 8 bits, allowing for a maximum number 256. When you multiply 97 and 101, you get 9797. The significant bits in the binary representation of 9797 are lost due to 8-bit arithmetic giving you 69 which is E
.