Last active
August 29, 2015 14:26
-
-
Save jmcd/9c494616080444d00194 to your computer and use it in GitHub Desktop.
Simple BCD coder
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 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)); | |
} | |
} | |
} |
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 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