Reputation: 21
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
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
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