简体   繁体   中英

How to convert byte array into Human readable format?

I am using "Blowfish" algorithm to encrypt and decrypt the contents of the text. 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 .

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.
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. 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 :

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. This even works on 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

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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