Convert a byte array to hex string {0x00, 0x01, (byte)0xff} -> "00 01 ff" - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Convert a byte array to hex string {0x00, 0x01, (byte)0xff} -> "00 01 ff"

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(ByteArrayToHexString(data));
    }/*  w w  w.ja va  2 s . co m*/

    /**
     * Convert a byte array to hex string
     * {0x00, 0x01, (byte)0xff}   -> "00 01 ff"
     */
    public static String ByteArrayToHexString(byte[] data) {
        final int len = 3 * data.length;
        final StringBuilder stringBuilder = new StringBuilder(len);
        for (byte b : data) {
            stringBuilder.append(Integer.toString((b & 0x000000ff) + 0x100,
                    16).substring(1));
            stringBuilder.append(" ");
        }
        stringBuilder.delete(len - 1, len);
        return stringBuilder.toString();
    }
}

Related Tutorials