一种BCD码转换的算法
#include "stdio.h"
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
/**
***************************************************************************************************
* @Brief Decimal convert BCD code
* @Param _Dec Decimal (Max: 2^64)
* _Buf BCD code buffer
* _Num Decimal digit
* @RetVal None
* @Note None
***************************************************************************************************
*/
void Dec_to_BCD(uint64_t _Dec, uint8_t* _Buf, uint8_t _Num)
{
uint8_t i, n;
uint8_t flag = 1; /* BCD码高低字节存放控制标志 */
/* 内部计算 _Dec 的位数,可省去形参 _Num */
#if 0
uint8_t _Num;
uint64_t temp = _Dec;
do {
_Num++;
temp /= 10;
} while(temp);
#endif
for (i = 0; i < _Num; i++) {
if (flag) {
/* 低字节 */
_Buf[i/2] = (_Dec % 10) & 0x0F;
flag = 0;
} else {
/* 高字节 */
_Buf[i/2] |= ((_Dec % 10) & 0x0F) << 4;;
flag = 1;
}
_Dec /= 10;
}
}
int main(void)
{
uint8_t i;
uint8_t buf[5] ={0};
printf("This is example!\n");
Dec_to_BCD(1234567890, buf, 10);
for (i = 0; i < 5; i++) {
printf("%#X\n", buf[i]);
}
return 0;
}
再牛逼的梦想也架不住傻逼似的坚持