I have an unsigned integer but when i print it out using %d there is sometimes a negative value there?
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).
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.
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."
UInt32 stands for unsigned integer. 3. It can store negative and positive integers.
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.
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With