[英]How do i convert binary-coded decimal to decimal in C?
所以我的任务是将BCD转换为十进制,但是问题是我不知道如何从第一个四进制转换到第二个四进制。 例如,BCD编号为10010011(十进制为93),我的代码适用于第一个quadd(1001),但是如何转换其他代码? 这是我尝试使用的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main(void) {
int bcd, bcd1, bcd2, bcd3, bcd4, zero, one, dec = 0;
char bcdstr[40];
printf("Type 2-10 number\n");
scanf_s("%d", &bcd);
snprintf(bcdstr, 40, "%d", bcd);
bcd1 = (bcd / 1000);
printf("%d\n", bcd1);
bcd2 = (bcd / 100) % 10;
printf("%d\n", bcd2);
bcd3= (bcd % 100) / 10;
printf("%d\n", bcd3);
bcd4 = ((bcd % 1000) % 100) % 10;
printf("%d\n", bcd4);
if (bcd1 == 1) dec = 8;
if (bcd2 == 1) dec = dec + 4;
if (bcd3 == 1) dec = dec + 2;
if (bcd4 == 1) dec = dec + 1;
if (dec > 9) printf("Not BCD!");
else printf("Decimal is %d", dec);
printf("\nstrlen is %d", strlen(bcdstr));
getchar();
}
您只需单独获取BCD的每个数字并将其添加到一个数字中:
unsigned bcd_to_decimal(unsigned bcd)
{
unsigned result = 0;
unsigned short exp = 1;
unsigned char ctr = 4, tmp;
while(ctr--)
{
tmp = bcd & 0xf;
if(tmp > 9)
printf("Not BCD!");
result += tmp * exp;
exp *= 10;
bcd >>= 4;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.