Convert Unsigned Int To Signed Int C


Answer :

It seems like you are expecting int and unsigned int to be a 16-bit integer. That's apparently not the case. Most likely, it's a 32-bit integer - which is large enough to avoid the wrap-around that you're expecting.



Note that there is no fully C-compliant way to do this because casting between signed/unsigned for values out of range is implementation-defined. But this will still work in most cases:



unsigned int x = 65529;
int y = (short) x; // If short is a 16-bit integer.


or alternatively:



unsigned int x = 65529;
int y = (int16_t) x; // This is defined in <stdint.h>


I know it's an old question, but it's a good one, so how about this?



unsigned short int x = 65529U;
short int y = *(short int*)&x;

printf("%d\n", y);


@Mysticial got it. A short is usually 16-bit and will illustrate the answer:



int main()  
{
unsigned int x = 65529;
int y = (int) x;
printf("%d\n", y);

unsigned short z = 65529;
short zz = (short)z;
printf("%d\n", zz);
}

65529
-7
Press any key to continue . . .




A little more detail. It's all about how signed numbers are stored in memory. Do a search for twos-complement notation for more detail, but here are the basics.



So let's look at 65529 decimal. It can be represented as FFF9h in hexadecimal. We can also represent that in binary as:



11111111 11111001



When we declare short zz = 65529;, the compiler interprets 65529 as a signed value. In twos-complement notation, the top bit signifies whether a signed value is positive or negative. In this case, you can see the top bit is a 1, so it is treated as a negative number. That's why it prints out -7.



For an unsigned short, we don't care about sign since it's unsigned. So when we print it out using %d, we use all 16 bits, so it's interpreted as 65529.



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable