Returns the specified data as hex sequence - Java java.lang

Java examples for java.lang:Hex

Description

Returns the specified data as hex sequence

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] data = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toHexString(data));
    }//from  ww  w.  j av  a 2 s  .  c  o  m

    /**
     * Returns the specified data as hex sequence
     *
     * @param data
     *            The data
     * @return a hex string
     */
    public static String toHexString(byte[] data) {
        final int n = data.length;
        final StringBuilder hex = new StringBuilder();

        for (int i = 0; i < n; i++) {
            final byte b = data[i];
            hex.append(String.format("%02x", b & 0xff));
        }

        return hex.toString();
    }
}

Related Tutorials