Convert byte array to Hex string using String.format - Java java.lang

Java examples for java.lang:String Hex

Description

Convert byte array to Hex string using String.format

Demo Code


//package com.java2s;
import java.math.BigInteger;

public class Main {
    public static void main(String[] argv) {
        byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toHex(bytes));
    }//from   w  w w. j  av a 2 s  .  co  m

    public static String toHex(byte[] bytes) {
        BigInteger bi = new BigInteger(1, bytes);
        String hex = bi.toString(16);
        int paddingLength = (bytes.length * 2) - hex.length();
        if (paddingLength > 0) {
            return String.format("%0" + paddingLength + "d", 0) + hex;
        } else {
            return hex;
        }
    }
}

Related Tutorials