I would like to use decimals represented in byte arrays (BCD format) to perform mathematical increments on the decimal values in the form of byte arrays.
An example is I would like to do 255 + 1
in maths which gives 256
. When done in a binary array format, the 255
value would be 00000000FF
and 1
is 0000000001
value in hexadecimal representation of bytes. The result to be expected would be 0000000100
.
My following code attempts to do a 5 byte array increment of 255
by 1
. My end results is 00000001FE
which the last byte 0xFE
is suppose to be 0x00
. How do I correct my algorithm to properly perform a 5 byte array increment by only using basic binary operands (the Java environment is embedded) ?
private static byte[] clkCtrCurr = new byte[5];
private static byte[] inc = {0x00, 0x00, 0x00, 0x00, 0x01};
private static byte buff;
private static byte carry;
public static void binAdd() {
buff = (byte) (clkCtrCurr[4] ^ inc[4]);
carry = (byte) (clkCtrCurr[4] & inc[4]);
clkCtrCurr[4] = buff;
clkCtrCurr[3] ^= carry;
buff = (byte) (clkCtrCurr[3] ^ inc[3]);
carry = (byte) (clkCtrCurr[3] & inc[3]);
clkCtrCurr[3] = buff;
clkCtrCurr[2] ^= carry;
buff = (byte) (clkCtrCurr[2] ^ inc[2]);
carry = (byte) (clkCtrCurr[2] & inc[2]);
clkCtrCurr[2] = buff;
clkCtrCurr[1] ^= carry;
buff = (byte) (clkCtrCurr[1] ^ inc[1]);
carry = (byte) (clkCtrCurr[1] & inc[1]);
clkCtrCurr[1] = buff;
clkCtrCurr[0] ^= carry;
clkCtrCurr[0] ^= inc[0];
}