Encodes byte sequence to string of a hexadecimal notation. - Java java.lang

Java examples for java.lang:byte Array to String

Description

Encodes byte sequence to string of a hexadecimal notation.

Demo Code


//package com.java2s;

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

    /**
     * Encodes byte sequence to string of a hexadecimal notation.
     *
     * @param bytes Byte sequence.
     * @return String of a hexadecimal notation.
     * @since 0.0.1
     */
    public static String encode(byte[] bytes) {
        if (bytes == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            builder.append(Integer.toHexString((b & 0xF0) >> 4));
            builder.append(Integer.toHexString(b & 0xF));
        }
        return builder.toString();
    }
}

Related Tutorials