C语言 打印无符号短值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5134779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing unsigned short values
提问by foo
unsigned short a;
char temp[] = "70000";
a = atoi(temp);
printf("a: %d\n", a);
Gives me the output a: 4464when it should be a: 70000Is there a better way to convert from ASCII to a decimal? The range of a unsigned short is 0 - 65535
a: 4464应该在什么时候给我输出a: 70000有没有更好的方法将 ASCII 转换为十进制?unsigned short 的范围是 0 - 65535
采纳答案by schnaader
You are answering the question yourself. The range of a unsigned shortis 0-65535, so 70000 doesn't fit into it (2 bytes), use a datatype with 4 bytes instead (unsigned intshould work, you can check the size with sizeof).
你自己在回答这个问题。a 的范围unsigned short是 0-65535,因此 70000 不适合它(2 个字节),请改用 4 个字节的数据类型(unsigned int应该可以,您可以使用 来检查大小sizeof)。
回答by T.J. Crowder
As schnaader said, you may be running into an overflow problem.
正如施纳德所说,您可能会遇到溢出问题。
But answering your printfquestion about outputting unsigned values, you want the umodifier (for "unsigned"). In this case, as Jens points out below, you want %hu:
但是在回答printf有关输出无符号值的问题时,您需要u修饰符(对于“无符号”)。在这种情况下,正如 Jens 在下面指出的那样,您需要%hu:
printf("a: %hu\n", a);
...although just %u(unsigned int, rather than unsigned short) would probably work as well, because the shortwill get promoted to intwhen it gets pushed on the stack for printf.
...虽然只是%u( unsigned int, 而不是unsigned short) 也可能会起作用,因为当它被推入堆栈时short将被提升为.intprintf
But again, that's only if the value 70000 will fit in an unsigned shorton your platform.
但同样,只有当值 70000 适合unsigned short您的平台时。

