Skip to content

Instantly share code, notes, and snippets.

@jmcd
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmcd/9c494616080444d00194 to your computer and use it in GitHub Desktop.
Save jmcd/9c494616080444d00194 to your computer and use it in GitHub Desktop.
Simple BCD coder
public class BcdCoderTests extends InstrumentationTestCase {
private int[][] decimalAndBcd = new int[][]{
{0, 0},
{1, 1},
{2, 2},
{3, 3},
{4, 4},
{5, 5},
{6, 6},
{7, 7},
{8, 8},
{9, 9},
{16, 10},
{17, 11},
{18, 12},
{19, 13},
{20, 14},
{21, 15},
{22, 16},
{23, 17},
{24, 18},
{25, 19},
{32, 20},
{33, 21},
{34, 22},
{35, 23},
{36, 24},
{37, 25},
{38, 26},
{39, 27},
{40, 28},
{41, 29},
{48, 30},
{49, 31}
};
public void testDecode() {
for (int[] pair : this.decimalAndBcd) {
int bcd = pair[0];
int decimal = pair[1];
Assert.assertEquals(decimal, SingleByteBcdCoder.decode((byte) bcd));
}
}
public void testEncode() {
for (int[] pair : this.decimalAndBcd) {
int bcd = pair[0];
int decimal = pair[1];
Assert.assertEquals(bcd, SingleByteBcdCoder.encode(decimal));
}
}
}
public class SingleByteBcdCoder {
public static byte encode(int i) {
int tens = i / 10;
int units = i - tens * 10;
return (byte) (tens << 4 | units);
}
public static int decode(byte b) {
int tens = b & 0xf0;
tens = tens >> 4;
int units = b & 0x0f;
return tens * 10 + units;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment