-
-
Save wjch/bb68d0ed0acd286e3fb9 to your computer and use it in GitHub Desktop.
BCD Conversion in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Various BCD Conversion util. methods */ | |
public class BCD { | |
/* | |
* long number to bcd byte array e.g. 123 --> (0000) 0001 0010 0011 | |
* e.g. 12 ---> 0001 0010 | |
*/ | |
public static byte[] DecToBCDArray(long num) { | |
int digits = 0; | |
long temp = num; | |
while (temp != 0) { | |
digits++; | |
temp /= 10; | |
} | |
int byteLen = digits % 2 == 0 ? digits / 2 : (digits + 1) / 2; | |
boolean isOdd = digits % 2 != 0; | |
byte bcd[] = new byte[byteLen]; | |
for (int i = 0; i < digits; i++) { | |
byte tmp = (byte) (num % 10); | |
if (i == digits - 1 && isOdd) | |
bcd[i / 2] = tmp; | |
else if (i % 2 == 0) | |
bcd[i / 2] = tmp; | |
else { | |
byte foo = (byte) (tmp << 4); | |
bcd[i / 2] |= foo; | |
} | |
num /= 10; | |
} | |
for (int i = 0; i < byteLen / 2; i++) { | |
byte tmp = bcd[i]; | |
bcd[i] = bcd[byteLen - i - 1]; | |
bcd[byteLen - i - 1] = tmp; | |
} | |
return bcd; | |
} | |
public static String BCDtoString(byte bcd) { | |
StringBuffer sb = new StringBuffer(); | |
byte high = (byte) (bcd & 0xf0); | |
high >>>= (byte) 4; | |
high = (byte) (high & 0x0f); | |
byte low = (byte) (bcd & 0x0f); | |
sb.append(high); | |
sb.append(low); | |
return sb.toString(); | |
} | |
public static String BCDtoString(byte[] bcd) { | |
StringBuffer sb = new StringBuffer(); | |
for (int i = 0; i < bcd.length; i++) { | |
sb.append(BCDtoString(bcd[i])); | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment