Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert byte array into Human readable format?

Tags:

java

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.

like image 740
Supereme Avatar asked Nov 10 '10 04:11

Supereme


People also ask

How can I convert byte size into a human readable format in Java?

private static Map<Long, String> DATA_MAP_BINARY_PREFIXES = new HashMap<Long, String>() {{ put(0L, "0 Bytes"); put(1023L, "1023 Bytes"); put(1024L, "1 KiB"); put(12_345L, "12.06 KiB"); put(10_123_456L, "9.65 MiB"); put(10_123_456_798L, "9.43 GiB"); put(1_777_777_777_777_777_777L, "1.54 EiB"); }};

Can we convert byte array to file in Java?

In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.


4 Answers

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));
like image 60
Mark Elliot Avatar answered Oct 05 '22 19:10

Mark Elliot


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

String value = new String(byteArray);
like image 30
Barun Avatar answered Oct 05 '22 18:10

Barun


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();
    }   
}
like image 22
Nikolaus Gradwohl Avatar answered Oct 05 '22 19:10

Nikolaus Gradwohl


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

[1, 2, 3, 4]
like image 30
Tag Avatar answered Oct 05 '22 18:10

Tag