Java 如何使用 System.out.println 以十六进制打印字节?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1748021/
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 print bytes in hexadecimal using System.out.println?
提问by dedalo
I've declared a byte array (I'm using Java):
我已经声明了一个字节数组(我使用的是 Java):
byte test[] = new byte[3];
test[0] = 0x0A;
test[1] = 0xFF;
test[2] = 0x01;
How could I print the different values stored in the array?
如何打印存储在数组中的不同值?
If I use System.out.println(test[0]) it will print '10'. I'd like it to print 0x0A
如果我使用 System.out.println(test[0]) 它将打印 '10'。我希望它打印 0x0A
Thanks to everyone!
谢谢大家!
采纳答案by bruno conde
System.out.println(Integer.toHexString(test[0]));
OR (pretty print)
或(漂亮的印刷品)
System.out.printf("0x%02X", test[0]);
OR (pretty print)
或(漂亮的印刷品)
System.out.println(String.format("0x%02X", test[0]));
回答by jeff porter
byte test[] = new byte[3];
test[0] = 0x0A;
test[1] = 0xFF;
test[2] = 0x01;
for (byte theByte : test)
{
System.out.println(Integer.toHexString(theByte));
}
NOTE: test[1] = 0xFF; this wont compile, you cant put 255 (FF) into a byte, java will want to use an int.
注意:测试[1] = 0xFF;这不会编译,您不能将 255 (FF) 放入一个字节中,java 将要使用 int。
you might be able to do...
你也许能做到……
test[1] = (byte) 0xFF;
I'd test if I was near my IDE (if I was near my IDE I wouln't be on Stackoverflow)
我会测试我是否在我的 IDE 附近(如果我在我的 IDE 附近,我就不会在 Stackoverflow 上)
回答by Carl Smotricz
for (int j=0; j<test.length; j++) {
System.out.format("%02X ", test[j]);
}
System.out.println();