c++typescastinginteger

How does typecasting between different sized integers work in C++?


Imagine: int full = static_cast<int>(uint8_t_var); Does anything actually happen under the hood here? If you're on a machine with 64 bit registers, I assume that the higher bits of uint8_t_var would reliably all be 0s. I imagine casting down would require masking out the upper bits for shifting behavior to work properly, but perhaps there's something I haven't considered that necessitates a mask of the upper bits of the 8 bit variable.


Solution

  • If you're on a machine with 64 bit registers

    Whether or not registers are used is irrelevant, as full and uint8_t_var are separate variables.

    I assume that the higher bits of uint8_t_var would reliably all be 0s.

    Converting a smaller integer type to a larger integer type will "extend" the value. As uint8_t_var is (presumably) an unsigned type, the extra bits in the larger type will be filled with 0s, yes. This is known as Zero Extension.

    If uint8_t_var were a signed type instead, then the extra bits of the larger integer type would get filled with the value of the sign bit of the smaller integer. This is known as Sign Extension.

    I imagine casting down would require masking out the upper bits for shifting behavior to work properly

    They are not simply masked, no.

    For signed types, if the value in the larger integer type is higher than the maximum value, or lower than the minimum value, that is representable in the smaller integer type, then the result will be truncated or undefined, depending on implementation.

    For unsigned types, the result will be the result of modulo arithmetic.

    Either way, the resulting value in the smaller integer type will not be the same as the original value.