user0712
user0712

Reputation: 21

How to convert binary array to a decimal number in C

I am facing difficulty in converting a binary array to a decimal number:

bin[8] = {10,00,00,10};

I want the equivalent of this array element as a decimal number, i.e. 130.

Upvotes: 0

Views: 8502

Answers (2)

Alex Liu
Alex Liu

Reputation: 105

I think you can follow this code:

int bin_to_dec(char *src, int bits){
    int i, n, sum = 0;
    for (i = 0; i < bits; i++) {
        n = *(src + i) - '0';
        sum += (n * (1 << (bits - (i + 1))));
    }
    return sum;
}

Upvotes: 0

Acorn
Acorn

Reputation: 26194

A standard solution goes like this:

int f(char s[])
{
    int n = 0;
    int i;

    for (i = 0; i < 8; ++i) {
        n <<= 1;
        n += s[i] - '0';
    }

    return n;
}

Upvotes: 1

Related Questions