C:打印“unsigned long"的正确方法十六进制 [英] C: Correct way to print "unsigned long" in hex

查看:732
本文介绍了C:打印“unsigned long"的正确方法十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,它获取一个 unsigned long 变量作为参数,我想以十六进制打印它.

I have a function that gets an unsigned long variable as parameter and I want to print it in Hex.

正确的做法是什么?

目前,我使用 printf%lx"

void printAddress(unsigned long address) {
    printf("%lx\n", address);
}

我应该为 unsigned 长十六进制寻找 printf 模式吗?(而不仅仅是上面提到的长十六进制")

Should I look for a printf pattern for unsigned long hex? (and not just "long hex" as mentioned above)

还是 printf 仅使用位将数字转换为十六进制?- 所以我无论如何都不应该关心这个标志?

Or does printf convert numbers to hex only using the bits? - so I should not care about the sign anyway?

这个问题源于一个困惑:十六进制是表示位的另一种方式,这意味着有符号/无符号数只是一种解释.类型是 unsigned long 的事实因此不会改变十六进制数字.Unsigned 只是告诉你如何在你的计算机程序中解释这些相同的位.

This question was rooted in a confusion: hex is another way to express bits, which means that signed/unsigned number is just an interpretation. The fact that the type is unsigned long therefore doesn't change the hex digits. Unsigned just tells you how to interpret those same bits in your computer program.

推荐答案

你做得对.

来自手册页:

o、u、x、x

unsigned int 参数被转换为无符号八进制 (o)、无符号十进制 (u) 或无符号十六进制(x 和 X)表示法.

The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (x and X) notation.

所以 x 的值应该总是 unsigned.要使其long 的大小,请使用:

So the value for x should always be unsigned. To make it long in size, use:

l

(ell) 以下整数转换对应于 long int 或 unsigned long int 参数 [...]

(ell) A following integer conversion corresponds to a long int or unsigned long int argument [...]

所以 %lxunsigned long.但是,地址(指针值)应该用 %p 打印并转换为 void *.

So %lx is unsigned long. An address (pointer value), however, should be printed with %p and cast to void *.

这篇关于C:打印“unsigned long"的正确方法十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆