问题
When trying to print 'UINT_MAX' all I get it -1, why is this? It's the only thing I have in my 'main()', a printf statement that prints 'UINT_MAX'
回答1:
You used the %d
format code, which interprets its argument as a signed int
. You're on a two's complement system, so UINT_MAX
(0xFFFFFFFF
), interpreted as a signed int
, is equal to -1
. If you want to print it interpreted as unsigned
, use %u
.
回答2:
You can print it with printf()
printf("%u\n", UINT_MAX);
You need to use u
specifier, man printf.
Why you get -1 with d
specifier? It's because of how work a signed integer in memory.
unsigned integer
start at 0, in memory it a simple binary system.
decimal => binary
- 1 => 1
- 2 => 10
- 8 => 1000
- 255 => 11111111
signed integer use a bit to be interpreted as a negative number, it's confusing because the max value of an unsigned int when it is interpreted like an int is -1.
example with 8 bit integer:
- -1 => 11111111
- -128 => 10000000
- -9 => 11110111
Like you see, the first bit is used to be the sign bit.
Try with this site
来源:https://stackoverflow.com/questions/41007976/when-trying-to-print-uint-max-i-get-1