#include <stdio.h>
// BCD到16进制转换
unsigned char bcd_to_hex(unsigned char bcd_val) {
return ((bcd_val / 10) << 4) + (bcd_val % 10);
}
// 16进制到BCD转换
unsigned char hex_to_bcd(unsigned char hex_val) {
return ((hex_val >> 4) * 10) + (hex_val & 0x0F);
}
int main() {
unsigned char bcd_val = 0x1A; // 示例BCD值 0001 1010
unsigned char hex_val = 0x1A; // 示例16进制值 0001 1010
// BCD到16进制转换
unsigned char hex_from_bcd = bcd_to_hex(bcd_val);
printf("BCD to Hex: 0x%02X -> 0x%02X\n", bcd_val, hex_from_bcd);
// 16进制到BCD转换
unsigned char bcd_from_hex = hex_to_bcd(hex_val);
printf("Hex to BCD: 0x%02X -> 0x%02X\n", hex_val, bcd_from_hex);
return 0;
}
|