Compute a String in HexDigit from the input. - Java java.lang

Java examples for java.lang:String Hex

Description

Compute a String in HexDigit from the input.

Demo Code


//package com.java2s;

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

    /**
     * Lower case Hex Digits.
     */
    private static final String HEX_DIGITS = "0123456789abcdef";
    /**
     * Byte mask.
     */
    private static final int BYTE_MSK = 0xFF;
    /**
     * Hex digit mask.
     */
    private static final int HEX_DIGIT_MASK = 0xF;
    /**
     * Number of bits per Hex digit (4).
     */
    private static final int HEX_DIGIT_BITS = 4;

    /**
     * Compute a String in HexDigit from the input.
     *
     * @param byteArray
     * a row byte array
     * @return a hex String
     */
    private static String toHexString(final byte[] byteArray) {
        StringBuilder sb = new StringBuilder(byteArray.length * 2);
        for (int i = 0; i < byteArray.length; i++) {
            int b = byteArray[i] & BYTE_MSK;
            sb.append(HEX_DIGITS.charAt(b >>> HEX_DIGIT_BITS)).append(
                    HEX_DIGITS.charAt(b & HEX_DIGIT_MASK));
        }
        return sb.toString();
    }
}

Related Tutorials