How to format numbers to a hex strings?

荒凉一梦 提交于 2019-12-19 05:12:55

问题


I want to format int numbers as hex strings. System.out.println(Integer.toHexString(1)); prints 1 but I want it as 0x00000001. How do I do that?


回答1:


Try this

System.out.println(String.format("0x%08X", 1));



回答2:


You can use the String.format to format an integer as a hex string.

   System.out.println(String.format("0x%08X", 1));

That is, pad with zeros, and make the total width 8. The 1 is converted to hex for you. The above line gives: 0x00000001 and

   System.out.println(String.format("0x%08X", 234));

gives: 0x000000EA




回答3:


From formatting syntax documented on Java's Formatter class:

Integer intObject = Integer.valueOf(1);
String s = String.format("0x%08x", intObject);
System.out.println(s);



回答4:


I don't know Java too intimately, but there must be a way you can pad the output from the toHexString function with a '0' to a length of 8. If "0x" will always be at the beginning, just tack on that string to the beginning.




回答5:


You can use a java.util.Formatter or the printf method on a PrintStream.



来源:https://stackoverflow.com/questions/13851743/how-to-format-numbers-to-a-hex-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!