aouainia
aouainia

Reputation: 21

binary string to decimal number in c

I can't figure out what's wrong with this code!
It returns 208 as a decimal where it should be 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);
}

Upvotes: 1

Views: 748

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136218

Alternatively, if you zero-terminate your string you can use strtol function with base 2, e.g.:

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

Upvotes: 1

Ctx
Ctx

Reputation: 18420

binstr[cpts] yields the ascii code of 0 or 1 (which is 0x30 or 0x31).

You need to use binstr[cpts] == '1' to convert a ascii '1' to the number 1 and everything else to 0 (assuming that no other characters may occur). Another option would be binstr[cpts] - '0'.

Btw, using the pow() function is disregarded for such cases, better substitute pow(2,x) by (1<<x).

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

There are many possibilities to make it look nicer, of course, the most obvious being (binstr[cpts] == '1') << x.

Furthermore, mind that your code expects exactly 8 binary digits to calculate the correct result.

Upvotes: 3

Related Questions