Java Hex Calculate toHexString(byte b[])

Here you can find the source of toHexString(byte b[])

Description

convert an array of bytes to an hexadecimal string

License

Open Source License

Parameter

Parameter Description
b bytes array to convert to a hexadecimal string

Return

a string

Declaration

public static String toHexString(byte b[]) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from  w ww  .j a  va  2 s  . c om*/
     * to hex converter
     */
    private static final char[] toHex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
            'f' };

    /**
     * convert an array of bytes to an hexadecimal string
     * @return a string
     * @param b bytes array to convert to a hexadecimal
     * string
     */
    public static String toHexString(byte b[]) {
        int pos = 0;
        char[] c = new char[b.length * 2];
        for (int i = 0; i < b.length; i++) {
            c[pos++] = toHex[(b[i] >> 4) & 0x0F];
            c[pos++] = toHex[b[i] & 0x0f];
        }
        return new String(c);
    }

    /**
     * Turns a long into a byte array, then applies
     * toHexString(byte[]).
     * @param aLong
     * @return
     */
    public static String toHexString(long aLong) {

        byte[] bytes = new byte[8];
        bytes[7] = (byte) ((aLong >>> 0) & 0xFF);
        bytes[6] = (byte) ((aLong >>> 8) & 0xFF);
        bytes[5] = (byte) ((aLong >>> 16) & 0xFF);
        bytes[4] = (byte) ((aLong >>> 24) & 0xFF);
        bytes[3] = (byte) ((aLong >>> 32) & 0xFF);
        bytes[2] = (byte) ((aLong >>> 40) & 0xFF);
        bytes[1] = (byte) ((aLong >>> 48) & 0xFF);
        bytes[0] = (byte) ((aLong >>> 56) & 0xFF);

        return toHexString(bytes);

    }

    /**
     * Turns a double into a byte array, then applies
     * toHexString(byte[]).
     * @param aLong
     * @return
     */
    public static String toHexString(double aDouble) {

        return toHexString(Double.doubleToLongBits(aDouble));

    }

    /**
     * Turns an int into a byte array, then applies
     * toHexString(byte[]).
     * @param anInt
     * @return
     */
    public static String toHexString(int anInt) {
        byte[] b = new byte[4];
        b[3] = (byte) (anInt & 0xFF);
        b[2] = (byte) ((anInt & 0xFF00) >> 8);
        b[1] = (byte) ((anInt & 0xFF0000) >> 16);
        b[0] = (byte) ((anInt & 0xFF000000) >> 24);
        return toHexString(b);
    }
}

Related

  1. toHexString(byte b)
  2. toHexString(byte b)
  3. toHexString(byte b)
  4. toHexString(byte b)
  5. toHexString(byte b[])
  6. toHexString(byte b[])
  7. toHexString(byte b[])
  8. toHexString(byte buffer[])
  9. toHexString(byte buffer[])