Created
November 6, 2014 11:01
-
-
Save avatsav/b5f9f9d32bde56eee79a to your computer and use it in GitHub Desktop.
intTo32bitBCD 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
public static byte[] intTo32BitBCD(Integer data) { | |
if (i == null) { | |
i = 0; | |
} | |
/* NumberFormat will format the integer and return a string with length 8 */ | |
NumberFormat numberFormat = NumberFormat.getNumberInstance(); | |
numberFormat.setMaximumFractionDigits(0); | |
numberFormat.setMinimumIntegerDigits(8); | |
numberFormat.setMaximumIntegerDigits(8); | |
numberFormat.setGroupingUsed(false); | |
String integerString = numberFormat.format(data); | |
//Calculate BCD :) | |
int size = integerString.length(); //always 8 | |
byte bcd[] = new byte[4]; | |
int index = 0; | |
boolean advance = size % 2 != 0; | |
for (char c : integerString.toCharArray()) { | |
byte tmp = (byte) (c - '0'); | |
if (advance) { | |
bcd[index++] |= tmp; | |
} else { | |
bcd[index] |= (byte) (tmp << 4); | |
} | |
advance = !advance; | |
} | |
return bcd; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment