如何将字节数组转换为人类可读格式?

Sup*_*eme 10 java

我使用"Blowfish"算法来加密和解密文本内容.我正在将加密的内容嵌入到图像中,但在提取时我得到的是字节数组,我将它传递给类Cipher的方法更新.

但是该方法返回了我想要转换回人类可读形式的字节数组.
当我使用FileOutputStream的write方法时,它在提供文件名时工作正常. 但现在我想以人类可读的格式在控制台上打印它.如何通过这个?我也尝试过ByteArrayOutputStream.但效果不佳.

谢谢.

Mar*_*iot 7

如果您只想查看数值,则可以遍历数组并打印每个字节:

for(byte foo : arr){
    System.out.print(foo + " ");
}
Run Code Online (Sandbox Code Playgroud)

或者,如果要查看十六进制值,可以使用printf:

System.out.printf("%02x ", foo);
Run Code Online (Sandbox Code Playgroud)

如果要查看字节数组所代表的字符串,您可以这样做

System.out.print(new String(arr));
Run Code Online (Sandbox Code Playgroud)


Bar*_*run 6

byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};

String value = new String(byteArray);
Run Code Online (Sandbox Code Playgroud)

  • 恕我直言,Blowfish 返回的字节数组可以返回完整字节范围内的字节值。此答案当前显示了“人类可读的子范围”中的示例字节数组。使用 `new String(byteArray);` 不一定(通常)产生人类可读的字符串。 (2认同)

Nik*_*ohl 6

您可以使用此方法将bytearray转换为包含字节十六进制值的字符串.这甚至适用于java <6

public class DumpUtil {

     private static final String HEX_DIGITS = "0123456789abcdef";

     public static String toHex(byte[] data) {
        StringBuffer buf = new StringBuffer();

        for (int i = 0; i != data.length; i++) {
            int v = data[i] & 0xff;

            buf.append(HEX_DIGITS.charAt(v >> 4));
            buf.append(HEX_DIGITS.charAt(v & 0xf));

            buf.append(" ");
        }

        return buf.toString();
    }   
}
Run Code Online (Sandbox Code Playgroud)