8421BCD码字节数组与字符串String/char[]的互转

8421BCD码字节数组:

用4位二进制数来表示1位十进制数(只能是0~9这10个数码),是一种二进制的数字编码形式。利用了四个位元来储存一个十进制的数码,使二进制十进制之间的转换得以快捷的进行。

BCD字节数组转为字符串:

/**
* BCD字节数组转为字符串
* @param bytes
* @return
*/
public static String bcd2String(byte[] bytes) {
    StringBuilder temp = new StringBuilder(bytes.length * 2);
    for (int i = 0; i < bytes.length; i++) {
        // 高四位
        temp.append((bytes[i] & 0xf0) >>> 4);
        // 低四位
        temp.append(bytes[i] & 0x0f);
    }
    return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp.toString().substring(1) : temp.toString();
}

BCD转char[]:


//仅支持0~9这10个数码
/** BCD转String */
public static String toString(byte[] bcd) {
    return new String(toChars(bcd));
}

/** BCD转char[] */
public static char[] toChars(byte[] bcd) {
    char[] chars = new char[bcd.length * 2];
    for (int i = 0, j = 0; i < bcd.length; i++) {
        chars[j++] = (char) (48 + (bcd[i] >> 4 & 0xf));
        chars[j++] = (char) (48 + (bcd[i] & 0xf));
    }
    return chars;
}

字符串转为BCD字节数组:

/**
* 字符串转为BCD字节数组
* @param str
* @return BCD字节数组
*/
public static byte[] stringBcd(String str) {
    //若为奇数,补0为偶
    if ((str.length() & 0x1) == 1) {
        str = "0" + str;
    }
    byte ret[] = new byte[str.length() / 2];
    byte bs[] = str.getBytes();
    for (int i = 0; i < ret.length; i++) {
        byte high = ascII2Bcd(bs[2 * i]);
        byte low = ascII2Bcd(bs[2 * i + 1]);
        ret[i] = (byte) ((high << 4) | low);
    }
    return ret;
}

public static byte ascII2Bcd(byte asc) {
    if ((asc >= '0') && (asc <= '9'))
        return (byte) (asc - '0');
    else if ((asc >= 'A') && (asc <= 'F'))
        return (byte) (asc - 'A' + 10);
    else if ((asc >= 'a') && (asc <= 'f'))
        return (byte) (asc - 'a' + 10);
    else
        return (byte) (asc - 48);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值