Java ASCII to Hex asciiToHex(byte[] src, int len, int padding)

Here you can find the source of asciiToHex(byte[] src, int len, int padding)

Description

ascii To Hex

License

Apache License

Declaration

public static byte[] asciiToHex(byte[] src, int len, int padding) 

Method Source Code

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

public class Main {

    public static byte[] asciiToHex(byte[] src, int len, int padding) {
        byte[] bcd = new byte[len];
        byte[] asc = null;
        if (padding == 0) {
            asc = lpBytes(src, len * 2, (byte) 0x30);
        } else {/* w w w. j  a v  a2  s .co  m*/
            asc = rpBytes(src, len * 2, (byte) 0x30);
        }
        for (int i = 0; i < len; i++) {
            bcd[i] = (byte) ((byte) byteToBcd(asc[i * 2]) << 4 ^ (byteToBcd(asc[i * 2 + 1]) & 0x0f));
        }
        return bcd;
    }

    private static byte[] lpBytes(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 < len; i++) {
            if (i >= (rlen - llen))
                des[i] = src[i - rlen + llen];
            else
                des[i] = fill;
        }
        return des;
    }

    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 byteToBcd(byte src) {
        byte re = src;
        if (src <= 0x39 && src >= 0x30)
            re = (byte) (src - 0x30);
        else if (src <= 0x46 && src >= 0x41)
            re = (byte) (src - 0x37);
        else if (src <= 0x66 && src >= 0x61)
            re = (byte) (src - 0x57);
        return re;
    }
}

Related

  1. ascii2Hex(byte[] in)
  2. Ascii2Hex(int len, byte data_in[], byte data_out[])
  3. ASCIIToHex(int args, int len)
  4. asciiToHex(String ascii)
  5. asciiToHex(String ascii)
  6. asciiToHex(String ascii)