Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c - integer downcast

About integer numbers downcasts in C, e.g.

An int value 000F'E000 downcast to short or unsigned short will become E000.
short -> -8192,
unsigned short -> 57344,

So does it simply cut the bits?

And what about upcasts? E.g. int -10 is ffffff81, what is the rule to cast to long long?


@Update

About upcasting, according to the answers I did some tests and found that with 2's complement it has the following rules:

    signed:
        positive -> positive: add 0 as prefix bits,
        negative -> negative: add 1 as prefix bits,
    unsigned:
        add 0 as prefix bits,

code:

// integer numbers, downcast & upcast,
#include <stdio.h>

void downcastTest() {
    int i = 127<<13;
    printf("%X, %hX, %hi\n", i, i, i);
}

void upcastTest() {
    int i = 127;
    int j = -127;
    printf("%x, %llx\n", i, (long long)i);
    printf("%x, %llx\n", j, (long long)j);
}

int main(int argc, char * argv[]) {
    downcastTest();
    upcastTest();
    return 0;
}
like image 660
user218867 Avatar asked Jan 11 '15 16:01

user218867


2 Answers

Downcasts

A cast to a smaller integer type discards the most significant (left-most as you'd write the full binary integer on paper) bits that are not present in the destination type.

Upcasts

An upcast to a larger integer is more complex:

  • For unsigned to unsigned types, it adds sufficient zero most-significant bytes; this always preserves the value.
  • For signed to signed types, it sign-extends the the source type (i.e. packs the new byte(s) with bits equal to the sign bit of the source integer); this always preserves the value, positive or negative
  • For unsigned to signed types, it effectively adds sufficient zero-most significant bytes; this always preserves the value, as in the nature of an upcast, there are always more bits in the destination, so there is always space for an extra sign 'bit'
  • For signed to unsigned types, it sign-extends, then casts; this cannot always preserve the value, as a negative value cannot be represented.
like image 198
abligh Avatar answered Oct 28 '22 14:10

abligh


Downcast cuts the bits, up-cast depends on "signedness". Up-cast on unsigned types adds zero bits to the value, up-cast on signed types replicates the sign bit. In this way, the expression has the same value before and after an upcast.

like image 31
Marian Avatar answered Oct 28 '22 12:10

Marian