如何在 Java 中使用具有长值的 printf() 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28538307/
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
How to use printf() method with long values in Java?
提问by Karthik Cherukuri
I remember that I did this in C but I couldn't get it work in Java.
我记得我是用 C 完成的,但我无法在 Java 中使用它。
How to print long values with printf() method in Java?
如何在 Java 中使用 printf() 方法打印长值?
I tried with below code what I actually need is to print the long value in hexadecimal way like below
我尝试使用下面的代码,我实际需要的是以十六进制方式打印长值,如下所示
long l = 32L -----> 0000000000000022
长 l = 32L -----> 0000000000000022
If I use %d then it prints integer value which I don't want...
如果我使用 %d 那么它会打印我不想要的整数值......
class TestPrintf()
{
public static void main(String[] args)
{
long l = 100L;
System.out.printf(“%l”+l); // Error unknown format exception
System.out.printf(“%d”+l); // Prints 100
System.out.printf(“%f”+l); // Unknown illegal format conversion float != java.lang.long
}
}
采纳答案by Andy Turner
If you want a 16-character zero-padded string, with A-F
in uppercase, prefixed by 0x
, you should use:
如果你想要一个 16 个字符的零填充字符串,A-F
大写,前缀为0x
,你应该使用:
System.out.printf("0x%016X", l);
回答by Crazyjavahacking
You need to put the actual argument to print as the next argument of a printf()
methods. Concatenating will not work.
您需要将要打印的实际参数作为方法的下一个参数printf()
。连接将不起作用。
System.out.printf("%d%n", 123); // for ints and longs
System.out.printf("%d%n", 12345L); // for ints and longs
System.out.printf("%f%n", (double) 12345L); // for floating point numbers
Full documentation in java.util.Formatter
完整文档在 java.util.Formatter