Convert Byte Array to Hex Value - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Convert Byte Array to Hex Value

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] buf = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int offset = 2;
        int length = 2;
        int value = 2;
        toHexValue(buf, offset, length, value);
    }/*from   ww  w .j  a v  a 2  s  .  c om*/

    /**
     * Valid hexadecimal digits added by zhangwei 20050824
     */
    static public final byte HEX_DIGITS[] = { (byte) '0', (byte) '1',
            (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6',
            (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b',
            (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' };

    /**
     * Convert Byte Array to Hex Value
     * 
     * @param buf
     *            Byte Array to convert to Hex Value
     * @param offset
     *            Starting Offset for Conversion
     * @param length
     *            Length to convery
     * @param value
     *            Hex Value
     */
    public static void toHexValue(byte[] buf, int offset, int length,
            int value) {
        do {
            buf[offset + --length] = HEX_DIGITS[value & 0x0f];
            value >>>= 4;
        } while (value != 0 && length > 0);

        while (--length >= 0) {
            buf[offset + length] = HEX_DIGITS[0];
        }
    }
}

Related Tutorials