Java Byte Array to Hex bytes2HexCharArr(byte[] bytes)

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

Description

bytes Hex Char Arr

License

Open Source License

Declaration

public static byte[] bytes2HexCharArr(byte[] bytes) 

Method Source Code

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

public class Main {
    /**/*from   w w  w. j a  v  a2s  .  c  o m*/
     * Just do new String for now. Needs real implementation
     * 
     * @param id
     * @return
     */
    static char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    public static byte[] bytes2HexCharArr(byte[] bytes) {
        if (bytes == null)
            return null;
        byte[] sb = new byte[bytes.length * 2];
        // int i = 0;
        // for (byte b : bytes) {
        // int bi = b & 0xff;
        // sb[i] = (byte)(hexArray[bi >> 4]); // /16
        // sb[i+1] = (byte)(hexArray[bi & 0xf]);// mod 16
        // i+=2;
        // }
        copy2Hex(bytes, sb, 0);
        return sb;
    }

    public static void copy2Hex(byte[] srcBytes, byte[] desArr, int desPos) {
        if (srcBytes == null)
            return;
        if (desArr == null)
            throw new RuntimeException("destination buffer cannot be null.");
        if ((desArr.length - desPos) < srcBytes.length * 2)
            throw new RuntimeException(
                    "destination buffer doens't have enough space for copying and convert to hex.");

        int i = desPos;
        for (byte b : srcBytes) {
            int bi = b & 0xff;
            desArr[i] = (byte) (hexArray[bi >> 4]); // /16
            desArr[i + 1] = (byte) (hexArray[bi & 0xf]);// mod 16
            i += 2;
        }
    }
}

Related

  1. bytes2Hex(byte[] byteArray)
  2. bytes2Hex(byte[] bytes)
  3. bytes2Hex(byte[] bytes)
  4. bytes2Hex(byte[] bytes)
  5. bytes2Hex(byte[] bytes)
  6. bytes2HexPP2(byte[] bytes)
  7. bytes2HexSplit(byte[] in, int wordlength)
  8. bytes2HexStr(byte[] bytes)
  9. bytes2HexStr(byte[] bytes)