简体   繁体   English

如何在C中将二进制编码的十进制转换为十进制?

[英]How do i convert binary-coded decimal to decimal in C?

So my task is to convert BCD to decimal, but the problem is I don't know how to go from the first tetrad to the second one. 所以我的任务是将BCD转换为十进制,但是问题是我不知道如何从第一个四进制转换到第二个四进制。 For example the BCD number is 10010011 (93 in decimal), my code works for the first tetrad(1001), but how do I convert the other ones? 例如,BCD编号为10010011(十进制为93),我的代码适用于第一个quadd(1001),但是如何转换其他代码? Here is a code I tried to work with: 这是我尝试使用的代码:

#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();
}

You just take each digit of the BCD individually and add it to a number: 您只需单独获取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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM