-2
int[] png = { -119, 80, 78, 71, 13, 10, 26, 10 };

should be equal to an array of string as follows.

89 50 4E 47 0D 0A 1A 0A

I have tried with Integer.toHexString(-119) but it end up converting into ffffff89 but it should be equal to 89.

Harin
  • 1
  • 3
    Possible duplicate of [Java code To convert byte to Hexadecimal](http://stackoverflow.com/questions/2817752/java-code-to-convert-byte-to-hexadecimal) – Jeremy Mar 05 '17 at 06:38

1 Answers1

0

StringBuffer and format() of String Class can help you here.

For example,

String.format("%02X ", value);

Here is how you can iterate through the array to convert it to Hex.

public class ConvertToHexaDecimal {

    static int[] png = { -119, 80, 78, 71, 13, 10, 26, 10 };

    public static void main(String[] args){
        StringBuilder sb = new StringBuilder();
        for (int value : png ) {
            sb.append(String.format("%02X ", value));
        }
        System.out.println(sb.toString());
    }
}
Pratik Ambani
  • 2,523
  • 1
  • 18
  • 28
  • private static String 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(digits.charAt(v >> 4)); buf.append(digits.charAt(v & 0xf)); } return buf.toString(); } This Worked ... :) – Harin Mar 05 '17 at 16:32