十进制转BCD C语言代码
时间: 2024-09-13 09:02:41 浏览: 50
在C语言中,将十进制数转换成BCD码(二进制编码的十进制数),通常会分为两个步骤:首先将每一位单独处理,然后组合成完整的BCD码。下面是一个简单的函数示例,它将一个整数按四位一组转换成BCD码:
```c
#include <stdio.h>
#define BCD nibble_to_bcd
// Function to convert a single nibble (4 bits) to BCD
unsigned char nibble_to_bcd(unsigned char n)
{
return ((n >= 0 && n <= 9) ? n * 2 : (n % 10 << 4) + (n / 10));
}
// Function to convert decimal integer to BCD
void dec_to_bcd(int num)
{
int bcd[5]; // Enough space for four nibbles plus one extra for sign
bcd[0] = (num / 1000) ? BCD(num / 1000) : 0;
bcd[1] = (num / 100) % 10 ? BCD((num / 100) % 10) : 0;
bcd[2] = (num / 10) % 10 ? BCD((num / 10) % 10) : 0;
bcd[3] = num % 10 ? BCD(num % 10) : 0; // No need to check as it's already within 0-9 range
bcd[4] = num < 0 ? -1 : 0; // For sign bit
printf("BCD representation of %d is ", num);
for (int i = 0; i < 4; i++)
printf("%02X ", bcd[i]); // Display in hexadecimal for easier viewing
}
int main()
{
int num = 12345;
dec_to_bcd(num);
return 0;
}
```
阅读全文