Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert unsigned int to signed int C

Tags:

I am trying to convert 65529 from an unsigned int to a signed int. I tried doing a cast like this:

unsigned int x = 65529; int y = (int) x; 

But y is still returning 65529 when it should return -7. Why is that?

like image 353
darksky Avatar asked Nov 29 '11 20:11

darksky


People also ask

How do I cast an unsigned int to signed int?

To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.

How do I convert signed to unsigned manually?

Mathematically, the conversion from signed to unsigned works as follows: (1) do the integer division of the signed integer by 1 + max , (2) codify the signed integer as the non-negative remainder of the division. Here max is the maximum integer you can write with the available number of bits, 16 in your case.

Is int in C unsigned or signed?

The int type in C is a signed integer, which means it can represent both negative and positive numbers. This is in contrast to an unsigned integer (which can be used by declaring a variable unsigned int), which can only represent positive numbers.


2 Answers

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> 
like image 71
Mysticial Avatar answered Sep 19 '22 13:09

Mysticial


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); 
like image 35
Subsentient Avatar answered Sep 18 '22 13:09

Subsentient