
1、BCD介紹
(1)BCD碼(Binary-Coded Decimal)亦稱二進碼十進數。用4位二進制數來表示1位十進制數中的0~9這10個數碼。用二進制編碼的十進制代碼。
(2)BCD碼可分為有權碼和無權碼兩類:有權BCD碼有8421碼、2421碼、5421碼,其中8421碼是最常用的;無權BCD碼有余3碼,余3循環碼等。
(3)BCD和十進制在線轉換工具網站https://www.osgeo.cn/app/s3130
2、BCDUtil
涉及的方法strToBcd、ascToBcd、bcdToStr
package com.test;
/**
* BCD 8421碼
*/
public class BCDUtil {
private BCDUtil(){};
/**
* 字符串轉BCD碼
* @param asc ASCII字符串
* @return BCD
*/
public static byte[] strToBcd(String asc) {
int len = asc.length();
int mod = len % 2;
if (mod != 0) {
asc = "0" + asc;
len = asc.length();
}
byte abt[] = new byte[len];
if (len >= 2) {
len >>= 1;
}
byte bbt[] = new byte[len];
abt = asc.getBytes();
int j, k;
for (int p = 0; p < asc.length() / 2; p++) {
if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
j = abt[2 * p] - '0';
} else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
j = abt[2 * p] - 'a' + 0x0a;
} else {
j = abt[2 * p] - 'A' + 0x0a;
}
if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
k = abt[2 * p + 1] - '0';
} else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
k = abt[2 * p + 1] - 'a' + 0x0a;
} else {
k = abt[2 * p + 1] - 'A' + 0x0a;
}
int a = (j << 4) + k;
byte b = (byte) a;
bbt[p] = b;
}
return bbt;
}
/**
* ASCII轉BCD
* @param ascii ASCII byte數組
* @return BCD
*/
public static byte[] ascToBcd(byte[] ascii) {
return ascToBcd(ascii, ascii.length);
}
/**
* ASCII轉BCD
* @param ascii ASCII byte數組
* @param ascLength 長度
* @return BCD
*/
public static byte[] ascToBcd(byte[] ascii, int ascLength) {
byte[] bcd = new byte[ascLength / 2];
int j = 0;
for (int i = 0; i < (ascLength + 1) / 2; i++) {
bcd[i] = ascToBcd(ascii[j++]);
bcd[i] = (byte) (((j >= ascLength) ? 0x00 : ascToBcd(ascii[j++])) + (bcd[i] << 4));
}
return bcd;
}
/**
* BCD轉ASCII字符串
* @param bytes BCD byte數組
* @return ASCII字符串
*/
public static String bcdToStr(byte[] bytes) {
char temp[] = new char[bytes.length * 2], val;
for (int i = 0; i < bytes.length; i++) {
val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
val = (char) (bytes[i] & 0x0f);
temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
}
return new String(temp);
}
/**------------------------Private method start-------------------------**/
/**
* 轉換單個byte為BCD
* @param asc ACSII
* @return BCD
*/
private static byte ascToBcd(byte asc) {
byte bcd;
if ((asc >= '0') && (asc <= '9')) {
bcd = (byte) (asc - '0');
}else if ((asc >= 'A') && (asc <= 'F')) {
bcd = (byte) (asc - 'A' + 10);
}else if ((asc >= 'a') && (asc <= 'f')) {
bcd = (byte) (asc - 'a' + 10);
}else {
bcd = (byte) (asc - 48);
}
return bcd;
}
}