[英]Why is the value of this uint32_t -2147483648?
Using gcc compiler, why is this uint32_t
-2147483648 when I set the MSB? 使用gcc编译器,为什么在设置MSB时此
uint32_t
-2147483648? It's unsigned - shouldn't it be positive? 它没有签名-不应该是肯定的吗?
#include <stdio.h>
#include <stdint.h>
#define BIT_SET(a,b) ((a) |= (1<<(b)))
int main()
{
uint32_t var = 0;
BIT_SET(var, 31);
printf("%d\n", var); //prints -2147483648
return 0;
}
printf()
doesn't know the type of something you pass it and has to trust you to use the correct conversion specifier . printf()
不知道您传递的内容的类型,必须信任您使用正确的转换说明符 。 But you don't. 但是你没有。 With
%d
, printf()
interprets your value as an int
. 使用
%d
, printf()
会将您的值解释为int
。
On a platform where unsigned int
is the same as uint32_t
(very common), you could use %u
instead. 在
unsigned int
与uint32_t
(非常常见)相同的平台上,可以改用%u
。 But beware this isn't portable, eg to platforms where int
only has 16 bits. 但是请注意,这不是可移植的,例如,在
int
只有16位的平台上。 The correct way to print an uint32_t
looks like this (you have to include inttypes.h
): 打印
uint32_t
的正确方法如下所示(您必须包含inttypes.h
):
printf("%" PRIu32 "\n", var);
See eg this inttypes.h
reference 请参见例如此
inttypes.h
参考
You are using wrong format specifier here. 您在此处使用了错误的格式说明符。
%d
is for int
type, ie, signed integer type. %d
用于int
类型,即有符号整数类型。
To print exact width variables, you need to use PRIuN
macros as format specifiers. 要打印精确的宽度变量,您需要使用
PRIuN
宏作为格式说明符。
For unsigned type 32 bit, that would be PRIu32
. 对于32位无符号类型,
PRIu32
。 For an exhaustive list, see chapter §7.8.1, C11
. 有关详细列表,请参见第7.8.1节
C11
。
Type of var
is uint32_t
. var
类型是uint32_t
。 But you are printing it using %d
which is undefined behaviour . 但是您正在使用
%d
打印它,这是未定义的行为 。 Use PRIu32
from <inttypes.h>
to print uint32_t
: 使用
<inttypes.h>
PRIu32
打印uint32_t
:
printf("%"PRIu32"\n",var);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.