Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Unsigned int providing a negative value?

Tags:

c

int

unsigned

I have an unsigned integer but when i print it out using %d there is sometimes a negative value there?

like image 264
Dannul Avatar asked Dec 02 '09 09:12

Dannul


People also ask

Is unsigned integer always positive?

Unsigned Integers (often called "uints") are just like integers (whole numbers) but have the property that they don't have a + or - sign associated with them. Thus they are always non-negative (zero or positive).

Can integer have negative value?

Definition of Integers An integer is a number with no decimal or fractional part and it includes negative and positive numbers, including zero. A few examples of integers are: -5, 0, 1, 5, 8, 97, and 3,043.

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 uint32_t be negative?

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


2 Answers

Printing %d will read the integer as a signed decimal number, regardless of its defined type.

To print unsigned numbers, use %u.

This happens because of C's way to handle variable arguments. The compiler just pulls values from the stack (typed as void* and pointing to the call stack) and printf has to figure out what the data contains from the format string you give it to.

This is why you need to supply the format string - C has no way of RTTI or a 'base class' (Object in Java, for example) to get a generic or predefined toString from.

like image 191
LiraNuna Avatar answered Sep 29 '22 23:09

LiraNuna


This should work:

unsigned int a;
printf("%u\n", a);

Explanation: On most architectures, signed integers are represented in two's complement. In this system, positive numbers less than 2**(N-1) (where N = sizeof(int)) are represented the same way regardless whether you are using an int or a unsigned int. However, if the number in your unsigned int is larger than 2**(N-1), it represents a negative signed number under two's complement -- which is what printf gave you when you passed it "%d".

like image 43
int3 Avatar answered Sep 29 '22 22:09

int3