1 #include "stdio.h" 2 3 typedef unsigned char uint8_t; 4 typedef unsigned short uint16_t; 5 typedef unsigned int uint32_t; 6 typedef unsigned long long uint64_t; 7 8 /** 9 *************************************************************************************************** 10 * @Brief Decimal convert BCD code 11 * @Param _Dec Decimal (Max: 2^64) 12 * _Buf BCD code buffer 13 * _Num Decimal digit 14 * @RetVal None 15 * @Note None 16 *************************************************************************************************** 17 */ 18 void Dec_to_BCD(uint64_t _Dec, uint8_t* _Buf, uint8_t _Num) 19 { 20 uint8_t i, n; 21 uint8_t flag = 1; /* BCD码高低字节存放控制标志 */ 22 23 /* 内部计算 _Dec 的位数,可省去形参 _Num */ 24 #if 0 25 uint8_t _Num; 26 uint64_t temp = _Dec; 27 do 28 { 29 _Num++; 30 temp /= 10; 31 }while(temp); 32 #endif 33 34 for(i = 0; i < _Num; i++) 35 { 36 if(flag) /* 低字节 */ 37 { 38 _Buf[i/2] = (_Dec % 10) & 0x0F; 39 flag = 0; 40 } 41 else /* 高字节 */ 42 { 43 _Buf[i/2] |= ((_Dec % 10) & 0x0F) << 4;; 44 flag = 1; 45 } 46 _Dec /= 10; 47 } 48 } 49 50 51 52 53 54 55 int main(void) 56 { 57 uint8_t i; 58 uint8_t buf[5] ={0}; 59 60 61 printf("This is example!\n"); 62 63 Dec_to_BCD(1234567890, buf, 10); 64 65 for(i = 0; i < 5; i++) 66 { 67 printf("%#X\n", buf[i]); 68 } 69 70 71 return 0; 72 }
原文地址:https://www.cnblogs.com/skullboyer/p/8136902.html
时间: 2024-10-19 18:18:45