How to print the data in byte array as characters?

JavaArrays

Java Problem Overview


In my byte array I have the hash values of a message which consists of some negative values and also positive values. Positive values are being printed easily by using the (char)byte[i] statement.

Now how can I get the negative value?

Java Solutions


Solution 1 - Java

How about Arrays.toString(byteArray)?

Here's some compilable code:

byte[] byteArray = new byte[] { -1, -128, 1, 127 };
System.out.println(Arrays.toString(byteArray));

Output:

[-1, -128, 1, 127]

Why re-invent the wheel...

Solution 2 - Java

If you want to print the bytes as chars you can use the String constructor.

byte[] bytes = new byte[] { -1, -128, 1, 127 };
System.out.println(new String(bytes, 0));

Solution 3 - Java

Well if you're happy printing it in decimal, you could just make it positive by masking:

int positive = bytes[i] & 0xff;

If you're printing out a hash though, it would be more conventional to use hex. There are plenty of other questions on Stack Overflow addressing converting binary data to a hex string in Java.

Solution 4 - Java

Try it:

public static String print(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    for (byte b : bytes) {
        sb.append(String.format("0x%02X ", b));
    }
    sb.append("]");
    return sb.toString();
}

Example:

 public static void main(String []args){
    byte[] bytes = new byte[] { 
        (byte) 0x01, (byte) 0xFF, (byte) 0x2E, (byte) 0x6E, (byte) 0x30
    };

    System.out.println("bytes = " + print(bytes));
 }

Output: bytes = [ 0x01 0xFF 0x2E 0x6E 0x30 ]

Solution 5 - Java

Try this one : new String(byte[])

Solution 6 - Java

byte[] buff = {1, -2, 5, 66};
for(byte c : buff) {
	System.out.format("%d ", c);
}
System.out.println();

gets you

1 -2 5 66 

Solution 7 - Java

in Kotlin you can use :

println(byteArray.contentToString())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser631785View Question on Stackoverflow
Solution 1 - JavaBohemianView Answer on Stackoverflow
Solution 2 - JavaPeter LawreyView Answer on Stackoverflow
Solution 3 - JavaJon SkeetView Answer on Stackoverflow
Solution 4 - JavaRobustView Answer on Stackoverflow
Solution 5 - JavaVinit PrajapatiView Answer on Stackoverflow
Solution 6 - JavaalphazeroView Answer on Stackoverflow
Solution 7 - JavaAlireza GhanbariniaView Answer on Stackoverflow