When an int is cast to a short and truncated, how is the new value determined?

后端 未结 6 465
借酒劲吻你
借酒劲吻你 2020-12-01 13:53

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

6条回答
  •  不思量自难忘°
    2020-12-01 14:13

    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

提交回复
热议问题