我有一个字节:
byte STX = 0x02;
使用printf
按原样打印它会返回0x02
这就是我想要的:
System.out.printf("0x%02X", STX);
但是,我想用下面或类似的字符串连接它:
System.out.println("Found " + STX + " at " + i);
但它返回整数值。因此,我如何打印一个字节并用字符串连接?
答案 0 :(得分:3)
尝试这种方式:
System.out.println("Found " + String.format("0x%02X", STX) + " at " + i);
甚至更好:
System.out.println(String.format("Found 0x%02X at %d", STX, i));
甚至更好:
System.out.printf("Found 0x%02X at %d%n", STX, i);
答案 1 :(得分:1)
System.out.println("Found " + String.format("0x%02X", STX) + " at " + i);
答案 2 :(得分:1)
不幸的是,这实际上是现有答案的副本,该答案被低估了......但正如您的评论现在表明您欢迎这样的选择......
您可以使用printf
格式化整个字符串:
System.out.printf("Found 0x%02X at %d%n", STX, i);
这里0x%02X
是您已经知道的部分; %d
是i
的格式说明符; %n
是特定于平台的换行符。
我发现在整个语句中使用一种格式更清晰:printf
/ String.format
格式化或字符串连接,而不是两者的混合。
如果您发现自己想要格式而不打印到控制台,只需使用String.format
代替:
String text = String.format("Found 0x%02X at %d", STX, i);
(假设在这种情况下你不想要行分隔符。)
有关格式字符串中的所有选项,请参阅Formatter
documentation。