0

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.

1
  • Your array contains the decimal numbers 10 and 0. If you want a binary number you'd need to represent it as a string, or an array of bits (0 or 1 only). Commented Mar 27, 2018 at 10:39

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.