87

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104

7 Answers7

288

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

Sjoerd
  • 74,049
  • 16
  • 131
  • 175
Bohemian
  • 412,405
  • 93
  • 575
  • 722
25

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));
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 16
    The constructor String(byte[], int) is deprecated. Use String(byte[], Charset) instead, for example new String(bytes, Charset.forName("ISO-8859-1")). – Klas Lindbäck Sep 02 '11 at 11:57
24

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 ]

Robust
  • 2,415
  • 2
  • 22
  • 37
22

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
11

Try this one : new String(byte[])

Vinit Prajapati
  • 1,593
  • 1
  • 17
  • 29
8
byte[] buff = {1, -2, 5, 66};
for(byte c : buff) {
    System.out.format("%d ", c);
}
System.out.println();

gets you

1 -2 5 66 
alphazero
  • 27,094
  • 3
  • 30
  • 26
1

in Kotlin you can use :

println(byteArray.contentToString())