C++中int转char时123456为何被转换为ASCII值64?
When you assign an integer value larger than char's range to a char variable, the conversion follows these clear rules:
- Char size context: On most systems,
charoccupies 8 bits. If unsigned, it holds values from 0–255; if signed, from -128–127. Either way, 123456 is far outside this range. - Modulo arithmetic is the key: For unsigned
char, the C++ standard requires converting larger integers using modulo 2^8 (256). For signedchar, pre-C20 this behavior was implementation-defined, but nearly all compilers used the same modulo logic—and C20 standardized this wrapping behavior for signed types too.
Let's break down the math for 123456:
- Calculate how many times 256 fits into 123456:
256 × 482 = 123392 - Subtract that product from the original value:
123456 - 123392 = 64
This remainder is the value stored in yourcharvariable. Since 64 falls within both signed and unsignedcharranges, the result is consistent either way.
Why only a warning, not an error?
C++ allows implicit narrowing conversions (like int to char when the value is out of range) but flags them as risky because they discard data. Compilers issue a warning (like -Wconstant-conversion here) to alert you to the potential problem, but don't block compilation by default. If you want to enforce errors for such cases, use flags like -Werror to turn warnings into errors, or use an explicit cast to make your intent clear.
The ASCII value 64 maps to the character '@', which is what your cout statement outputs.
内容的提问来源于stack exchange,提问作者Tarun Malviya

