简体   繁体   English

C Unsigned int提供负值?

[英]C Unsigned int providing a negative value?

我有一个无符号整数,但是当我使用%d打印出来时,有时会出现负值吗?

Printing %d will read the integer as a signed decimal number, regardless of its defined type. 打印%d将读取整数作为带符号的十进制数,而不管其定义的类型如何。

To print unsigned numbers, use %u . 要打印无符号数字,请使用%u

This happens because of C's way to handle variable arguments. 这是因为C处理变量参数的方式。 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. 编译器只是从堆栈中提取值(键入为void*并指向调用堆栈), printf必须从您给它的格式字符串中找出数据包含的内容。

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. 这就是您需要提供格式字符串的原因 - C无法使用RTTI或“基类”(例如Java中的Object )来获取通用或预定义的toString

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 . 在这个系统中,无论是使用int还是unsigned int ,小于2**(N-1) (其中N = sizeof(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" . 但是,如果unsigned int中的数字大于2**(N-1) ,则表示在二进制补码下的负数有符号数 - 这是printf在您传递"%d"

%d means printf will interpret the value as an int(which is signed). %d表示printf将该值解释为int(已签名)。 use %u if it is an unsigned int. 如果它是unsigned int,请使用%u。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM