Java Hex Calculate toHex(byte[] value)

Here you can find the source of toHex(byte[] value)

Description

Return value as hex.

License

Open Source License

Declaration

private static String toHex(byte[] value) 

Method Source Code

//package com.java2s;
/*//from  w w  w  . j  a v a2s.co  m
 * Copyright 2000-2013 Enonic AS
 * http://www.enonic.com/license
 */

public class Main {
    /**
     * Hex characters.
     */
    private final static char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();

    /**
     * Return value as hex.
     */
    private static String toHex(byte[] value) {
        char[] chars = new char[value.length * 2];

        for (int i = 0; i < value.length; i++) {
            int a = (value[i] >> 4) & 0x0F;
            int b = value[i] & 0x0F;

            chars[i * 2] = HEX_CHARS[a];
            chars[i * 2 + 1] = HEX_CHARS[b];
        }

        return new String(chars);
    }

    /**
     * Return value as hex.
     */
    public static String toHex(short value) {
        byte[] bytes = new byte[2];

        bytes[0] = (byte) ((value >> 8) & 0xFF);
        bytes[1] = (byte) (value & 0xFF);

        return toHex(bytes);
    }

    /**
     * Return value as hex.
     */
    public static String toHex(int value) {
        byte[] bytes = new byte[4];

        bytes[0] = (byte) ((value >> 24) & 0xFF);
        bytes[1] = (byte) ((value >> 16) & 0xFF);
        bytes[2] = (byte) ((value >> 8) & 0xFF);
        bytes[3] = (byte) (value & 0xFF);

        return toHex(bytes);
    }

    /**
     * Return value as hex.
     */
    public static String toHex(long value) {
        byte[] bytes = new byte[8];

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

        return toHex(bytes);
    }
}

Related

  1. toHex(byte[] text)
  2. toHex(byte[] v)
  3. toHex(byte[] val)
  4. toHex(byte[] val, int start, int len)
  5. toHex(byte[] value)
  6. toHex(char c)
  7. toHex(final byte b)
  8. toHex(final byte b)
  9. toHex(final byte... bin)