When trying to print UINT_MAX I get -1 [duplicate]

血红的双手。 提交于 2019-12-13 10:02:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!