Can someone clarify what happens when an integer is cast to a short
in C? I\'m using Raspberry Pi, so I\'m aware that an int
is 32 bits, and theref
Truncation happens in CPU registers. These have different sizes: 8/16/32/64 bits. Now, you can imagine a register like:
<--rax----------------------------------------------------------------> (64-bit)
<--eax----------------------------> (32-bit)
<--ax-----------> (16-bit)
<--ah--> <--al--> (8-bit high & low)
01100011 01100001 01110010 01110010 01111001 00100000 01101111 01101110
x
is first given the 32 bit value 0x1248642
. In memory*, it'll look like:
-----------------------------
| 01 | 24 | 86 | 42 |
-----------------------------
31..24 23..16 15..8 7..0
Now, the compiler loads x
in a register. From it, it can simply load the least significant 16 bits (namely, ax
) and store them into sx
.
*Endianness is not taken into account for the sake of simplicity