C语言 如何将 unsigned int 格式化为 8 位十六进制数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3531970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:14:27  来源:igfitidea点击:

How to format unsigned int into 8 digit hexadecimal number?

cformattingprintf

提问by citronas

I want to format an unsigned int to an 8 digit long string with leading zeroes.

我想将一个 unsigned int 格式化为一个带有前导零的 8 位长字符串。

This is what I have so far:

这是我到目前为止:

  unsigned int number = 260291273;
  char output[9];
  sprintf(output, "%x", number);
  printf("%s\n", output); // or write it into a file with fputs

Prints "f83bac9", but I want "0f83bac9". How can I achieve the formatting?

打印“f83bac9”,但我想要“0f83bac9”。我怎样才能实现格式化?

回答by PaulJWilliams

Use "%08x" as your format string.

使用“%08x”作为格式字符串。

回答by Frxstrem

You can use zero-padding by specifying 0and the number of digits you want, between %and the format type.

您可以通过指定0您想要的位数%和格式类型来使用零填充。

For instance, for hexadecimal numbers with (at least) 8 digits, you'd use %08x:

例如,对于(至少)8 位的十六进制数,您可以使用%08x

printf("%08x", number);

Output (if numberis 500):

输出(如果number是 500):

000001f4

000001f4