Java Convert via ByteBuffer hexToAscii(byte[] src)

Here you can find the source of hexToAscii(byte[] src)

Description

hex To Ascii

License

Apache License

Declaration

public static byte[] hexToAscii(byte[] src) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.nio.ByteBuffer;

public class Main {

    public static byte[] hexToAscii(byte[] src) {
        byte[] asc = new byte[src.length * 2];
        asc = rpBytes(src, src.length * 2, (byte) 0x00);
        for (int i = 0; i < src.length; i++) {
            asc[i * 2] = bcdToByte((byte) (src[i] >> 4 & 0x0f));
            asc[i * 2 + 1] = bcdToByte((byte) (src[i] & 0x0f));
        }/*  www.  j a va 2s.c o m*/
        return asc;
    }

    public static byte[] hexToAscii(ByteBuffer src, int len) {
        byte[] tmp = new byte[len];
        System.arraycopy(src.array(), 0, tmp, 0, src.limit());
        return hexToAscii(tmp);
    }

    private static byte[] rpBytes(byte[] src, int len, byte fill) {
        byte[] des = new byte[len];
        int llen = src.length > len ? len : src.length;
        // int rlen = src.length < len ? len : src.length;
        for (int i = 0; i < llen; i++) {
            if (i < llen)
                des[i] = src[i];
            else
                des[i] = fill;
        }
        return des;
    }

    private static byte bcdToByte(byte src) {
        byte re = src;
        if (src <= 0x09 && src >= 0x00)
            re = (byte) (src + 0x30);
        else if (src <= 0x0f && src >= 0x0a)
            re = (byte) (src + 0x37);
        return re;
    }
}

Related

  1. hexDump(byte... b)
  2. hexDump(byte[] buffer)
  3. hexStringToBytes(String hexString)
  4. hexStrToStr(String hexStr)
  5. hexToBytes(String hexStr)
  6. hexToBytes(String hexString)
  7. intArrayFromBytes(byte[] bytes)
  8. intArrayToByteArray(int[] intArray)