Binary Coded Decimal-BCD

Binary Coded Decimal-BCD

Introduction

BCD code (Binary-Coded Decimal) is also known as binary-coded decimal or binary-to-decimal code. This encoding method uses four bits to store a decimal digit, allowing for quick conversion between binary and decimal.

This encoding technique is most commonly used in the design of accounting systems, as accounting often requires accurate calculations of long numerical strings. Compared to the general floating-point notation, using BCD code can preserve the accuracy of the value and avoid the time consumed by the computer when performing floating-point operations. In addition, BCD encoding is also commonly used for other calculations that require high precision.

BCD code is a four-bit binary code, which means converting decimal numbers into binary, but with a slight difference from the ordinary conversion. Each decimal digit from 0-9 corresponds to a four-bit binary code. The correspondence is as follows: decimal 0 corresponds to binary 0000; decimal 1 corresponds to binary 0001…9 corresponds to 1001. The next number 10 is represented by two of the aforementioned codes. 10 is represented as 00010000, which means that BCD code generates a carry when it encounters 1001, unlike the ordinary binary code that generates a carry only when it reaches 1111.

Method

String strForTest = "123456ABCDEF";
		
//Convert to BCD
byte[] bcd = BCD.strToBcd(strForTest);
//Decode BCD
String str = BCD.bcdToStr(bcd);
Assert.assertEquals(strForTest, str);