1. Introduction to BCD code
BCD code (Binary-Coded Decimal) is called binary code, which uses 4-digit binary numbers to represent the 10 digits 0~9 in the 1-digit decimal number. It is the most commonly used type of decimal code.
In this encoding method, each "1" of the binary code represents a fixed value. Add up the binary numbers represented by each "1" to get the decimal number it represents. Because each "1" in the code represents the numbers "8", "4", "2" and "1" from left to right, it is named 8421 code. The decimal number represented by each "1" is called the weight of this bit. Because the weight of each bit is fixed, the 8421 code is a constant weight code.
BCD codes can be divided into two categories: authorized codes and unauthorized codes:
- The authorized BCD codes include 8421 code, 2421 code and 5421 code, among which 8421 code is the most commonly used BCD code.
- Unauthorized BCD codes include remainder 3 codes, remainder 3 cyclic codes, etc.
By analogy with 8421BCD code, we can get 5421 code and 2421 code.
It can be seen that the 8421 code, the 5241 code and the 2421 code are all decimal codes, but the weight of the rightmost digit is different.
In the picture, you can see that the BCD codes of several digits from 0 to 9 are converted in the normal binary form, and the BCD codes starting from ten start to be different .
BCD code: represents a number using four binary digits as one unit. For example: the BCD code of the decimal number 10 is 0001 0000; obviously the last four digits of 0000 represent the ones digit of the decimal system, and 0001 is the tens digit. The same goes for converting hexadecimal to BCD.
2. Conversion between BCD code and decimal system
Convert 8421 code to decimal number
unsigned char bcd_to_hex(unsigned char data)
{
unsigned char temp;
temp = ((data>>4)*10 + (data&0x0f));
return temp;
}
Convert decimal number to 8421 code
unsigned char hex_to_bcd(unsigned char data)
{
unsigned char temp;
temp = (((data/10)<<4) + (data%10));
return temp;
}
Attachment: The conversion relationship between several code systems
Decimal | binary | 8421 codes | 5421 codes | 2421 codes | Three more yards | remainder cyclic code |
---|---|---|---|---|---|---|
0 | 0000 | 0000 | 00000 | 0000 | 0011 | 0010 |
1 | 0001 | 0001 | 0001 | 0001 | 0100 | 0110 |
2 | 0010 | 0010 | 0010 | 0010 | 0101 | 0111 |
3 | 0011 | 0011 | 0011 | 0011 | 0110 | 0101 |
4 | 0100 | 0100 | 0100 | 0100 | 0111 | 0100 |
5 | 0101 | 0101 | 1000 | 1011 | 1000 | 1100 |
6 | 0110 | 0110 | 1001 | 1100 | 1001 | 1101 |
7 | 0111 | 0111 | 1010 | 1101 | 1010 | 1111 |
8 | 1000 | 1000 | 1011 | 1110 | 1011 | 1110 |
9 | 1001 | 1001 | 1100 | 1111 | 1100 | 1010 |