Java – How to convert byte array to Hex

Here are two Java examples of converting byte array byte[] to Hexadecimal.

  • Apache Commons Codec
  • Integer
Possible duplicate
Please refer this for more code snippets – Convert String to Hex in Java

1. Apache Commons Codec

The easiest way.

pom.xml

  <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.14</version>
  </dependency>
HexUtils.java

package com.mkyong;

import org.apache.commons.codec.binary.Hex;

public class HexUtils {

    public static void main(String[] args) {

        String input = "I Love Java!";
        System.out.println("input : " + input);

        // utf encoding
        //String result = convertBytesToHex(input.getBytes(StandardCharsets.UTF_8));

        String result = convertBytesToHex(input.getBytes());
        System.out.println("result : " + result);

    }

    public static String convertBytesToHex(byte[] bytes) {

        char[] chars = Hex.encodeHex(bytes);
        return new String(chars);

    }
}

Output


input : I Love Java!
result : 49204c6f7665204a61766121

2. Integer

This example converts (widen) byte to int, and then use the Integer.toHexString to convert the int (decimal) into a Hexadecimal formatted String.

HexUtils2.java

package com.mkyong;

public class HexUtils2 {

    public static void main(String[] args) {

        String input = "I Love Java!";
        System.out.println("input : " + input);

        // utf encoding
        //String result = convertBytesToHex(input.getBytes(StandardCharsets.UTF_8));

        String result = convertBytesToHex(input.getBytes());
        System.out.println("result : " + result);

    }

    public static String convertBytesToHex(byte[] bytes) {

        StringBuilder result = new StringBuilder();

        for (byte temp : bytes) {

            int decimal = (int) temp & 0xff;  // bytes widen to int, need mask, prevent sign extension

            String hex = Integer.toHexString(decimal);

            result.append(hex);

        }
        return result.toString();


    }
}

Output


input : I Love Java!
result : 49204c6f7665204a61766121

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
newest oldest most voted
rico
Guest
rico

if (hex.length() == 1) sb.append(‘0’);
I don’t understand why need append a ‘0’

Joost de Folter
Guest
Joost de Folter

Nice article, however method 2 lacks padding – use this instead (this also removes the need to convert from byte to integer):
String.format(“%02x”, b)