Java Byte Array Encode encodeHex(byte[] bytes)

Here you can find the source of encodeHex(byte[] bytes)

Description

encode Hex

License

Apache License

Return

specified bytes encoded as string of hexadecimal digits

Declaration

public static String encodeHex(byte[] bytes) 

Method Source Code


//package com.java2s;
/*/*  ww  w  .j a v a2s.co  m*/
 *  Copyright Gergely Nagy <greg@webhejj.hu>
 *
 *  Licensed under the Apache License, Version 2.0; 
 *  you may obtain a copy of the License at:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 */

import java.io.UnsupportedEncodingException;

public class Main {
    private static final byte[] HEX_CHAR_TABLE = { (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' };

    /** @return specified bytes encoded as string of hexadecimal digits */
    public static String encodeHex(byte[] bytes) {

        if (bytes == null) {
            return "";
        }
        try {
            byte[] hex = new byte[2 * bytes.length];
            int index = 0;

            for (byte b : bytes) {
                int v = b & 0xFF;
                hex[index++] = HEX_CHAR_TABLE[v >>> 4];
                hex[index++] = HEX_CHAR_TABLE[v & 0xF];
            }
            return new String(hex, "ASCII");
        } catch (UnsupportedEncodingException e) {
            // should never happen, but still
            throw new RuntimeException("Could not encode to hex", e);
        }
    }
}

Related

  1. encodeByteArray(DataOutputStream out, byte[] bytes)
  2. encodeBytes(byte[] source, int off, int len)
  3. encodeCompositeAlways(List bytesList)
  4. encodeDataWithCharsetInMetaTag(byte[] data)
  5. encodeHex(byte[] bytes)