1

Suppose I have something like this:

unsigned int x = (unsigned int)SomeLong;

What exactly happens if SomeLong doesn't fit in 4 bytes? What does the new memory layout look like? How exactly does casting a number to a smaller size number in C work? What happens?

  • There's two different questions here: what happens in the abstract machine (which can be answered according to the C standard), and how this is implemented on a particular actual machine (you'll have to specify one). – Nate Eldredge Jul 10 '20 at 00:25
  • @NateEldredge So you're implying that different machines implement casting to smaller sizes differently? The answer I shared Q&A style was on MacOS, GCC. –  Jul 10 '20 at 00:26
  • 1
    Abstractly, they all truncate the most significant bits; this is guaranteed by the C standard. How that actually happens - what instructions are executed, what is physically stored in memory - is machine dependent. – Nate Eldredge Jul 10 '20 at 00:30
  • Incidentally, the situation for signed integers is completely different than for unsigned. – Nate Eldredge Jul 10 '20 at 00:30

1 Answers1

0

It truncates the memory. This is shown by this program, which shows the binary representation of the long, and then the binary representation of the long cast to a smaller int:

#include <stdio.h>
void Print8Byte(unsigned long Value) {
    for (unsigned char i = 0; i < 64; i++) {
        union {
            unsigned long Value;
            unsigned First:1;
        } Cast = {.Value = Value>>i};
        putchar('0'+Cast.First);
    }
    putchar('\n');
}
int main(int argc, char *argv[]) {
    unsigned long Num = 0x284884848; //Arbitrary Value
    Print8Byte(Num);
    Print8Byte((unsigned int)Num);
}

Result:

0001001000010010000100010010000101000000000000000000000000000000 0001001000010010000100010010000100000000000000000000000000000000

  • 1
    The statement that “It truncates memory,” although crude, is effectively true for conversions between unsigned types. It is not necessarily true for conversions between other types, and the answer should clarify that. Also, the code used in this answer is not a good demonstration. It prints the bits in the reverse of the usual order (without notifying the reader of this), and the use of the bit-field is not guaranteed by the C standard to work as desired (and is totally unnecessary, as `Value & 1` would suffice to extract the desired bit). – Eric Postpischil Jul 10 '20 at 10:58