Suppose there is the following code :
{
unsigned int var = 0x12345678;// assuming 4 bytes
return int;
}
void bar()
{
unsigned short res = foo(); //assuming short is 2 bytes
}
What can be the expected value of res?
CodePudding user response:
There are some issues with your code (no int foo()
, and return int
). I'm sure someone will edit.
C99 says:
6.3.1.3 Signed and unsigned integers [..] if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
So, assuming unsigned short
on your platform has a range of 0..65535, the value of res would be 0x12345678 - 65536*n, or 0x12345678 % 65536 = 0x5678.
CodePudding user response:
Size of int is 32 bit and size of short is 16 bit. Then the value of variable res will be 0x5678.
CodePudding user response:
The last 16 bits should be used as the value of the unsigned short (res).
0x12345678 is 10010001101000101011001111000.
That would likely make the short be 0101011001111000 = 0x5678
CodePudding user response:
Follow on question...
I only have access to a 'Little Endian' machine. As such, I am getting what I expect with this:
int main() {
uint32_t var = 0x12345678;
uint16_t *p = (uint16_t *)&var;
printf( "%X %X\n", var, *p );
p ;
printf( "%X %X\n", var, *p );
return 0;
}
Output:
12345678 5678
12345678 1234
Would someone with a 'Big Endian' machine please confirm that the 'uint16's are 'swapped' with the same code executing.
Thank you...
I will delete this after there is a response...