%04X 在 C 中的含义以及如何在 java 中编写相同的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9902301/
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-10-30 22:49:25  来源:igfitidea点击:

Meaning of %04X in C and how to write the same in java

javac

提问by Rog Matthews

In the java project i am working on, some portion of the project was written previously by someone else in C and now i need to write the same in Java.

在我正在处理的 java 项目中,该项目的某些部分以前是由其他人用 C 编写的,现在我需要用 Java 编写相同的内容。

There is a statement in C code for printing to a file:

C 代码中有一条语句用于打印到文件:

fprintf(ff, "%04X ", image[y*width+x]);

Firstly i am not sure about the meaning of %04X. I think it means that if image[i]has length five or more then print only leftmost four chararacters. To do the same in Java i thought about masking the value using andoperation

首先,我不确定%04X. 我认为这意味着如果image[i]长度为五个或更多,则只打印最左边的四个字符。为了在 Java 中做同样的事情,我想过使用and操作来屏蔽值

 image[i] & 0xFFFF

Can someone please tell me the correct meaning of %04Xand how to do the same in Java? Thanks.

有人可以告诉我%04X在 Java 中的正确含义以及如何做同样的事情吗?谢谢。

回答by Andreas Dolk

The value is formatted as a hexadecimal integer with four digits and leading zeros. Java uses the same format string syntax. You can find it in the javaDoc of Formatter.

该值的格式为带有四位数字和前导零的十六进制整数。Java 使用相同的格式字符串语法。您可以在.java 文档中Formatter找到它。

Excerpt:

摘抄:

'x', 'X'     integral    The result is formatted as a hexadecimal integer

A related functions are

一个相关的函数是

// create a String with the formatted value.
String formatted = String.format("%04X ", image[y*width+x]);

// write a formatted value to the console (*)
System.out.printf("%04X ", image[y*width+x]);

(*) - write it to the PrintStreamSystem.outwhich is usuallythe console but can be redirected to a file or something else

(*) -它写入PrintStreamSystem.out这是通常的控制台,但可以重定向到文件或其他什么东西

回答by Some programmer dude

Lets break the format code "%04X"into its separate parts:

让我们将格式代码"%04X"分解为单独的部分:

  • The Xmeans that it will print an integer, in hexadecimal, large Xfor large hexadecimal letters
  • The 4means the number will be printed left justified with at least four digits, print spaces if there is less than four digits
  • The 0means that if there is less than four digits it will print leading zeroes.
  • X意味着它将打印一个整数,以十六进制表示,大X的十六进制字母
  • 4数量将被打印装置左对齐,且至少四位数字,空格打印如果有不足4位
  • 0意味着如果少于四位数,它将打印前导零。

回答by Thomas Padron-McCarthy

The X in %04X means hexadecimal, with ABCDEF instead of abcdef, and the 04 means print at leastfour digits, padding with leading zeros. It will use more digits if needed.

%04X 中的 X 表示十六进制,用 ABCDEF 代替 abcdef,04 表示打印至少四位数字,用前导零填充。如果需要,它将使用更多数字。