简体   繁体   English

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

[英]How to convert byte array into Human readable format?

I am using "Blowfish" algorithm to encrypt and decrypt the contents of the text. 我使用“Blowfish”算法来加密和解密文本内容。 I am embedding the encrypted contents in the image but while extracting I am getting the byte array which I am passing it to method update of class Cipher . 我正在将加密的内容嵌入到图像中,但在提取时我得到的是字节数组,我将它传递给类Cipher的方法更新

But the method returns me byte array which I want to convert back into Human readable form. 但是该方法返回了我想要转换回人类可读形式的字节数组。
When I use write method of FileOutputStream it is working fine when a filename is provided. 当我使用FileOutputStream的 write方法时,它在提供文件名时工作正常。
But now I want to print it on the console in the human readable format. 但现在我想以人类可读的格式在控制台上打印它。 How to get through this? 如何通过这个? I have tried for ByteArrayOutputStream too. 我也尝试过ByteArrayOutputStream。 But didn't work well. 但效果不佳。

Thank you. 谢谢。

If all you want to do is see the numeric values you can loop through the array and print each byte: 如果您只想查看数值,则可以遍历数组并打印每个字节:

for(byte foo : arr){
    System.out.print(foo + " ");
}

Or if you want to see hex values you can use printf : 或者,如果要查看十六进制值,可以使用printf

System.out.printf("%02x ", foo);

If you want to see the string that the byte array represents you can just do 如果要查看字节数组所代表的字符串,您可以这样做

System.out.print(new String(arr));

You can convert the bytearray into a string containing the hex values of the bytes using this method. 您可以使用此方法将bytearray转换为包含字节十六进制值的字符串。 This even works on java < 6 这甚至适用于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();
    }   
}
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};

String value = new String(byteArray);
byte[] data = new byte[] {1, 2, 3, 4};
System.out.printf( Arrays.toString( data ) );

[1, 2, 3, 4]

It's better to do a hexDump that byte array 做一个字节数组的hexDump更好

private static final byte[] HEX_CHAR = new byte[] { '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public static final String dumpBytes(byte[] buffer) {
        if (buffer == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.setLength(0);
        for (int i = 0; i < buffer.length; i++) {
            sb.append((char) (HEX_CHAR[(buffer[i] & 0x00F0) >> 4]))
                    .append((char) (HEX_CHAR[buffer[i] & 0x000F])).append(' ');
        }
        return sb.toString();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM