gpt4 book ai didi

Why do int32_t and int16_t have same number of bits in printf output?(为什么int32_t和int16_t在printf输出中具有相同的位数?)

转载 作者:bug小助手 更新时间:2023-10-25 18:18:26 24 4
gpt4 key购买 nike



#include <stdio.h>
#include <stdint.h>

int main()
{
uint32_t a = 0xF0FF1FFF;
printf("a = 0x%x\n",a);
uint16_t b = a;
printf("b = 0x%x\n",b);


int32_t c = 0xF0FF8FFF;
printf("c = 0x%x\n",c);
int16_t d = c;
printf("d = 0x%x\n",d);

int32_t e = d;
printf("e = 0x%x\n",e);

return 0;
}

output:

输出:


a = 0xf0ff1fff
b = 0x1fff
c = 0xf0ff8fff
d = 0xffff8fff
e = 0xffff8fff

In this example, why does d print 32 bits unlike b?

在本例中,为什么d打印32位而不是b?


更多回答

Because it's implicitly converted to int.

因为它被隐式转换为int。

The "%x" treats the respective argument as unsigned int. It's UB if you pass something with a different type. Use "%" PRIu32 for a value of type uint32_t. See <inttypes.h> pubs.opengroup.org/onlinepubs/9699919799/basedefs/…

“%x”将各自的参数视为无符号整型。如果您传递的是不同类型的内容,则为UB。使用“%”pru32作为uint32_t类型的值。请参阅pubs.opengroup.org/onlinepubs/9699919799/basedefs/…

@pmg: You are right.

@PMG:你说得对。

How do I get in hexadecimal format then?

那我怎么才能得到十六进制格式呢?

@SreerajChundayil And now you do. Just understand that printf is not required to do what you want when you pass an int to a %x format. You should cast it to unsigned when passing it.

@SreerajChundayil,现在你做到了。只需理解,当您将int传递给%x格式时,并不需要printf来执行您想要的操作。在传递时,您应该将其转换为未签名。

优秀答案推荐

When a type smaller than int (like e.g. int16_t often is) is passed to a vararg function function like printf, it is promoted to an int.

当小于int的类型(例如,通常是int16_t)被传递给像print tf这样的vararg函数时,它将被提升为int。


This promotion includes sign extension, so a negative number still is the same negative number.

此促销包括符号扩展,因此负数仍然是相同的负数。


And using two's complement system, when the high bit is set, that indicates a negative number. So e.g. 0xf8ff will be promoted to 0xfffff8ff.

而使用二的补码系统,当高位被设置时,这表示负数。因此,例如0xf8ff将提升为0xfffff8ff。


This is what happens here.

这就是这里发生的事情。


To print an int16_t as hexadecimal, use the PRIx16 macro from <inttypes.h>:

要将int16_t打印为十六进制,请使用 中的PRIx16宏:


printf("d = %" PRIx16 "\n", d);

更多回答

Yes, I was trying to understand the sign extension with these examples. To print now I will have to cast to unsigned char* and print?

是的,我试图通过这些例子来理解符号扩展。要现在打印,我必须转换为未签名的字符*并打印?

@SreerajChundayil Added example on how to print a int16_t value in hexadecimal form.

@SreerajChundayil添加了如何以十六进制格式打印int16_t值的示例。

PRIx16 is for uint16_t and should not be used with int16_t without converting it to uint16_t first. A C implementation would be within its rights (confirming to the C standard) to print a negative int16_t value passed for PRIx16 with the same preceding f characters in OP’s example.

PRIx16用于uint16_t,如果不先将其转换为uint16_t,则不应与int16_t一起使用。C实现将在其权限范围内(符合C标准)打印为PRIx16传递的负int16_t值,其中包含OP示例中相同的前面的f字符。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com