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;
}
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.
An upcast to a larger integer is more complex:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With