非压缩的BCD码以8位为一组表示一个十进制数,8位中的低4位表示8421
的BCD码,而高4位则没有意义,那么:
public byte[] ToBCD(byte val) {
string str = val.ToString();
byte[] res = new byte[str.Length];
for (int i = 0; i < str.Length; i++) {
res[res.Length - 1 - i] = (byte) (str[i] - 48);
}
return res;
}
public byte FromBCD(byte[] vals) {
StringBuilder sb = new StringBuilder();
for (int i = vals.Length - 1; i >= 0; i--) {
sb.Append((char)(vals[i] + 48));
}
return Byte.Parse(sb.ToString());
}
的BCD码,而高4位则没有意义,那么:
public byte[] ToBCD(byte val) {
string str = val.ToString();
byte[] res = new byte[str.Length];
for (int i = 0; i < str.Length; i++) {
res[res.Length - 1 - i] = (byte) (str[i] - 48);
}
return res;
}
public byte FromBCD(byte[] vals) {
StringBuilder sb = new StringBuilder();
for (int i = vals.Length - 1; i >= 0; i--) {
sb.Append((char)(vals[i] + 48));
}
return Byte.Parse(sb.ToString());
}
public static int ToBCD(byte val) {
int res = 0;
int bit = 0;
while (val >= 10) {
res |= (val % 10 << bit);
val /= 10;
bit += 4;
}
res |= val << bit;
return res;
}
public static byte FromBCD(int vals) {
int c = 1;
byte b = 0;
while (vals > 0) {
b += (byte) ((vals & 0xf) * c);
c *= 10;
vals >>= 4;
}
return b;
}
long res = 0;
int bit = 0;
while (val >= 10) {
res |= (val % 10 << bit);
val /= 10;
bit += 4;
}
res |= val << bit;
return res;
}
public static long FromBCD(long vals) {
long c = 1;
long b = 0;
while (vals > 0) {
b += ((vals & 0xf) * c);
c *= 10;
vals >>= 4;
}
return b;
}