Question

I'm just trying to get some clarification about the rules when assigning a smaller bit-size value like a short to a larger one like an int or a double. Assuming a 6-bit machine using two's complement arithmetic for signed integers, what happens when I cast a smaller number of bits to a larger number of bits? Does it add all zeros or all ones to the end or the beginning? Not sure, any help would be appreciated. I.e:

short num = -3;
int y = num;

"num" in binary = 101, does y = 000101 or 101000 or 111101...etc?

What's the rule for casting to a larger number of bits?

Thank you!

Was it helpful?

Solution

In your example num would be sign-extended to fit in six bits, this means the sign bit is copied into the upper 3 bits of y. Since num is negative its sign bit is '1' and the result is 111101.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top