繁体   English   中英

二进制字符串到c中的十进制数

[英]binary string to decimal number in c

我无法弄清楚这段代码有什么问题!
它以十进制形式返回 208,它应该是 0

typedef unsigned char uchar;

int CONVERTION_BinStrToDecimal(char* binstr) //transform a inary string to a decimal number
{
    int cpts = 0;
    unsigned char dec = 0;
    uchar x = 0;
    for (cpts = 0; cpts <= 7; cpts++) {
        x = 7 - cpts;
        dec += (binstr[cpts]*pow(2,x));
    }
    return dec;
}

int main()
{
    uchar decimal = 0;
    char bin[8] = "00000000"; //example
    decimal = CONVERTION_BinStrToDecimal(bin);
    printf("%d", decimal);
}

binstr[cpts]生成01 (即 0x30 或 0x31)的 ascii 代码。

您需要使用binstr[cpts] == '1'将 ascii '1' 转换为数字 1,将其他所有内容转换为0 (假设不会出现其他字符)。 另一种选择是binstr[cpts] - '0'

顺便说一句,在这种情况下不考虑使用pow()函数,最好用(1<<x)替换pow(2,x) (1<<x)

for (cpts = 0; cpts <= 7; cpts++) {
    x = 7 - cpts;
    dec += ((binstr[cpts] == '1')*(1 << x));
}

有很多方法可以让它看起来更好,当然,最明显的是(binstr[cpts] == '1') << x

此外,请注意您的代码需要精确的 8 个二进制数字来计算正确的结果。

或者,如果您以零结尾您的字符串,您可以使用以 2 为基数的strtol函数,例如:

char bin[9] = "00000000";
decimal = strtol(bin, NULL, 2);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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