Binary coded decimal

From Lazer Swarm Wiki
Jump to navigation Jump to search

Binary coded decimal (BCD) uses four bits holding the values 0-9 to represent each digit of a decimal value. Each byte can hold two decimal digits. The protocol uses the value 0xFF to indicate that some values are unlimited.

BCD Decimal
Hex Dec Hex Dec
0x00 0 0x00 0
0x09 9 0x09 9
0x10 16 0x0A 10
0x16 22 0x10 16
0x99 153 0x63 99
0xFF 255 Unlimited

Here is an example of how to convert to and from binary coded decimal.

byte ToDecimal(byte bcd)
{
	if (bcd == 0xff) return bcd;
	return (((bcd >> 4) & 0xf) * 10) + (bcd & 0xf);
}

byte ToBinaryCodedDecimal(byte dec)
{
	if (dec == 0xff) return dec;
	return (byte)(((dec / 10) << 4) | (dec % 10));
}