Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when I assign a negative value to an unsigned int? [duplicate]

Tags:

Possible Duplicate:
signed to unsigned conversion in C - is it always safe?

Let's say I declare a variable of type unsigned int : unsigned int x = -1;

Now -1 in two's complement (assuming 32 bit machine) is 0xFFFFFFFF. Now when I assigned this value to x, did the value 0x7FFFFFFF get assigned to x?

If it were so, then printf ("%d",x); would have printed the decimal equivalent of 0x7FFFFFFF, right? But, clearly this isn't happening, as the value that gets printed is -1. What am I missing here?

Edit: I know that we can use the %u format specifier to print unsigned values. But that doesn't help answer the question above.

like image 657
n0nChun Avatar asked Aug 22 '11 19:08

n0nChun


People also ask

How is the negative value converted to the unsigned data types?

The representation in 2s complement is not mandated by the standard but the algorithm to convert to unsigned is: "the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the newtype until the value is in the range of the newtype."

Can an unsigned long be negative?

Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).

Can uint32_t be negative?

UInt32 stands for unsigned integer. 3. It can store negative and positive integers.

What happens if you set an unsigned type to a negative value in C++?

An unsigned integer will never be a negative value, the smallest value it can be is 0 (zero). The values you get are not garbage. Assigning -1 to an unsigned type will give you the maximum value that variable can hold. Assigning -2 to an unsigned type will give the maximum value that variable can hold minus 1.


1 Answers

The "%d" format is for (signed) int values. If you use it with an unsigned value, it could print something other than the actual value. Use "%u" to see the actual value, or %x to see it in hexadecimal.

In the declaration

unsigned int x = -1; 

the expression -1 is of type int, and has the value -1. The initializer converts this value from int to unsigned int. The rules for signed-to-unsigned conversion say that the value is reduced modulo UINT_MAX + 1, so -1 will convert to UINT_MAX (which is probably 0xffffffff or 4294967295 if unsigned int is 32 bits).

You simply cannot assign a negative value to an object of an unsigned type. Any such value will be converted to the unsigned type before it's assigned, and the result will always be >= 0.

like image 60
Keith Thompson Avatar answered Oct 19 '22 07:10

Keith Thompson