Convert four-byte decimal to BCD code

Convert four-byte decimal to BCD code

What is BCD code?

BCD code (Binary-Coded Decimal‎), using 4-digit binary numbers to represent 10 numbers from 0 to 9 in a decimal number, is a binary digital encoding form, using binary-coded decimal codes. The encoding form of BCD code uses four bits to store a decimal number, so that the conversion between binary and decimal can be carried out quickly. This coding technique is most often used in the design of accounting systems, because accounting systems often require accurate calculations on long strings of numbers. Compared with the general floating-point notation method, the BCD code can not only preserve the accuracy of the value, but also save the time spent on making the computer perform floating-point operations. In addition, BCD encoding is also commonly used for other calculations that require high precision.

How to convert?

To put it simply, if there is a decimal number 1049,
how to express it in BCD code? 0001 0000 0100 1001 converted to hexadecimal is 0x1049
How to realize it with code?
Here is the code directly, if you don’t understand, you can leave a message, and the test passed here.

static uint32_t DEC2BCD(uint32_t dec)  
{
    
      
	uint8_t u4,u3,u2,u1;
	if(dec<100)
    return (dec+(dec/10)*6);
	else if(dec<10000)
	{
    
    
		u2 = dec/100;
		u1 = dec%100;
		return (u2+(u2/10)*6)<<8|(u1+(u1/10)*6);
	}
	else if(dec<1000000)
	{
    
    
		u3 = dec/10000;
		u2 = dec/100%100;
		u1 = dec%100;
		return (u3+(u3/10)*6)<<16 | (u2+(u2/10)*6)<<8|(u1+(u1/10)*6);
	}
	else if(dec<100000000)
	{
    
    
		u4 = dec/1000000;
		u3 = dec/10000%100;
		u2 = dec/100%100;
		u1 = dec%100;
		return (u4+(u4/10)*6)<<24 | (u3+(u3/10)*6)<<16 | (u2+(u2/10)*6)<<8 | (u1+(u1/10)*6);
	}
	else
		return 0;
} 

Guess you like

Origin blog.csdn.net/weixin_42163707/article/details/120460348