我需要将一个有符号的值转换成一个无符号的值,当我将MSB赋值为1时,我发现uint32_t以某种方式被签名了。
在这段代码中,我展示了我的意思。测试1/2是为了表明这不仅仅是一个printf问题,也是一个不道德的问题。
#include <stdio.h>
#include <inttypes.h>
void main() {
int reg1S = 0xfffffff4;
int reg2S = 0xfffffff2;
uint32_t reg1U = 0xfffffff4;
uint32_t reg2U = 0xfffffff2;
uint8_t test1,test2;
test1 = (reg1S < reg2S ? 1:0);
test2 = (reg1U < reg2U ? 1:0);
printf("signed = %d \t",test1);
printf("unsigned = %d \n", test2);
printf("reg1S= %d \t", reg1S);
printf("reg1U= %d \n", reg1U);
printf("reg2S= %d \t", reg2S);
printf("reg2U= %d \n", reg2U);
}这是代码输出的内容
signed = 0 unsigned = 0
reg1S= -12 reg1U= -12
reg2S= -14 reg2U= -14注意:对于8位或16位无符号整数,它不能做到这一点,只有32位和64位
发布于 2021-11-25 21:31:10
%d用于打印带符号的类型。要打印无符号类型,请使用%u。
此外,当传递给printf时,小于int的类型将被提升为该类型,这就是为什么您在这些类型中看不到这种行为的原因。
发布于 2021-11-25 22:29:22
使用correct formats for fixed size integers
#include <stdio.h>
#include <inttypes.h>
void main() {
int32_t reg1S = 0xfffffff4; \\ <- implementation defined
int32_t reg2S = 0xfffffff2; \\ <- implementation defined
uint32_t reg1U = 0xfffffff4;
uint32_t reg2U = 0xfffffff2;
printf("reg1S= %"PRIi32" \t", reg1S);
printf("reg1U= %"PRIu32" \n", reg1U);
printf("reg2S= %"PRIi32" \t", reg2S);
printf("reg2U= %"PRIu32" \n", reg2U);
}https://stackoverflow.com/questions/70117417
复制相似问题