简体   繁体   English

C:printf 与 typedef unsigned long long int

[英]C: printf with typedef unsigned long long int

I have a typedef that contains a 64bit memory address in hex, but using %x with printf is giving me the following error:我有一个 typedef,其中包含一个 64 位的 memory 地址(十六进制),但是将%xprintf一起使用会给我以下错误:

error: format '%x' expects argument of type 'unsigned int', but argument 4 has type 'address'\

This is my declaration of the typedef:这是我对 typedef 的声明:

typedef unsigned long long int address;

How can I print this hexadecimal value?如何打印这个十六进制值? Thanks!谢谢!

Edit: the memory address is not a pointer, I am reading hexadecimal values from another file and need to store these 64bit addresses numerically using the typedef I defined.编辑:memory 地址不是指针,我正在从另一个文件中读取十六进制值,需要使用我定义的 typedef 以数字方式存储这些 64 位地址。

The %x conversion specifier expects its corresponding argument to have type unsigned int . %x转换说明符期望其对应的参数具有unsigned int类型。 To print an unsigned long long , you need to use the length modifier ll , or %llx .要打印unsigned long long ,您需要使用长度修饰符ll%llx

Handy Table方便的桌子

Length Modifier        Type
–––––––––––––––        ––––
             ll        (unsigned) long long
              l        (unsigned) long
              h        (unsigned) short
             hh        (unsigned) char
              j        intmax_t, uintmax_t
              z        size_t
              t        ptrdiff_t
              L        long double

So to format an unsigned char value as hex, you'd use %hhx or %hhX .因此,要将unsigned char值格式化为十六进制,您可以使用%hhx%hhX To format a short as decimal, you'd use %hd .要将short格式化为十进制,您可以使用%hd To format an unsigned long as octal, you'd use %lo .要将unsigned long格式化为八进制,您可以使用%lo

Gratuitous rant无端的咆哮

You've just illustrated why I tend to avoid using the typedef facility for primitive types.您刚刚说明了为什么我倾向于避免将typedef工具用于原始类型。

You've created what's known as a leaky abstraction - you've ostensibly created a new type to represent an address value, but you have to know that it has been implemented as an unsigned long long in order to use it correctly.您已经创建了所谓的泄漏抽象——您表面上创建了一个新类型来表示地址值,但您必须知道它已经实现为unsigned long long以便正确使用它。

If you're going to create an abstract type, you need to go all the way and create abstractions (functions, macros, etc.) for all operations on that type, including input and output (and assignment, and validation, etc.).如果要创建抽象类型,则需要一路 go 并为该类型上的所有操作创建抽象(函数、宏等),包括输入和 output(以及赋值和验证等) .

It's generally not worth the effort for primitive types, so I'd avoid using typedef for this purpose.通常不值得为原始类型付出努力,因此我会避免为此目的使用typedef

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

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