如何打印字节和字符串?

时间:2014-02-01 18:31:32

标签: java byte printf output system.out

我有一个字节:

byte STX = 0x02;

使用printf按原样打印它会返回0x02这就是我想要的:

System.out.printf("0x%02X", STX);

但是,我想用下面或类似的字符串连接它:

System.out.println("Found " +  STX + " at " + i);

但它返回整数值。因此,我如何打印一个字节并用字符串连接?

3 个答案:

答案 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)

使用String.format

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是您已经知道的部分; %di的格式说明符; %n是特定于平台的换行符。

我发现在整个语句中使用一种格式更清晰:printf / String.format格式化字符串连接,而不是两者的混合。

如果您发现自己想要格式而不打印到控制台,只需使用String.format代替:

String text = String.format("Found 0x%02X at %d", STX, i);

(假设在这种情况下你不想要行分隔符。)

有关格式字符串中的所有选项,请参阅Formatter documentation

相关问题