What are the format specifiers to use for printf when dealing with types such as int32_t, uint16_t and int8_t, etc.?
在处理int32_t,uint16_t和int8_t等类型时,printf使用哪些格式说明符?
Using %d, %i, etc. will not result in a portable program. Is using the PRIxx macros the best approach?
使用%d,%i等不会产生便携式程序。使用PRIxx宏是最好的方法吗?
2 个解决方案
#1
Is using the PRIxx macros the best approach?
使用PRIxx宏是最好的方法吗?
As far as I know, yes.
据我所知,是的。
Edit: another solution is to cast to a type that is at least as wide as the one you want to print. For example int
is at least 2 bytes wide, to can print a int16_t
with printf("%d\n", (int)some_var)
.
编辑:另一种解决方案是转换为至少与要打印的类型一样宽的类型。例如int至少为2个字节宽,可以用printf打印int16_t(“%d \ n”,(int)some_var)。
#2
Yes, if you're using the new types, you really should be using the new format specifiers.
是的,如果你正在使用新类型,你真的应该使用新的格式说明符。
That's the best way to do it since the implementation has already done the grunt work of ensuring the format strings will be correct for the types.
这是最好的方法,因为实现已经完成了确保格式字符串对于类型正确的繁重工作。
So, for example:
所以,例如:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main (void) {
int32_t i32 = 40000;
printf ("%d\n", i32); // might work.
printf ("%" PRId32 "\n", i32); // will work.
return 0;
}
shows both ways of doing it.
显示了这两种方式。
However, there's actually no guarantee that the first one will do as you expect. On a system with 16-bit int
types for example, you may well get a different value.
但是,实际上并不能保证第一个会像你期望的那样。例如,在具有16位int类型的系统上,您可能会获得不同的值。
#1
Is using the PRIxx macros the best approach?
使用PRIxx宏是最好的方法吗?
As far as I know, yes.
据我所知,是的。
Edit: another solution is to cast to a type that is at least as wide as the one you want to print. For example int
is at least 2 bytes wide, to can print a int16_t
with printf("%d\n", (int)some_var)
.
编辑:另一种解决方案是转换为至少与要打印的类型一样宽的类型。例如int至少为2个字节宽,可以用printf打印int16_t(“%d \ n”,(int)some_var)。
#2
Yes, if you're using the new types, you really should be using the new format specifiers.
是的,如果你正在使用新类型,你真的应该使用新的格式说明符。
That's the best way to do it since the implementation has already done the grunt work of ensuring the format strings will be correct for the types.
这是最好的方法,因为实现已经完成了确保格式字符串对于类型正确的繁重工作。
So, for example:
所以,例如:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main (void) {
int32_t i32 = 40000;
printf ("%d\n", i32); // might work.
printf ("%" PRId32 "\n", i32); // will work.
return 0;
}
shows both ways of doing it.
显示了这两种方式。
However, there's actually no guarantee that the first one will do as you expect. On a system with 16-bit int
types for example, you may well get a different value.
但是,实际上并不能保证第一个会像你期望的那样。例如,在具有16位int类型的系统上,您可能会获得不同的值。