Skip to content

Instantly share code, notes, and snippets.

@avatsav
Created November 6, 2014 11:01
Show Gist options
  • Save avatsav/b5f9f9d32bde56eee79a to your computer and use it in GitHub Desktop.
Save avatsav/b5f9f9d32bde56eee79a to your computer and use it in GitHub Desktop.
intTo32bitBCD Java
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