Gabi
Gabi

Reputation: 9

How to convert binary array to decimal in C

I am trying to convert a binary array to decimal Here is what i have to convert, binTodec[8] = {1,1,1,1,0,0,1,1}

I have started with for(int i=0; i<8; i++)

Is there anybody that can help me

Upvotes: 1

Views: 1030

Answers (2)

imjlfish
imjlfish

Reputation: 79

One method is to calculate from the most significant bit to the least significant bit.

If binTodec[0] is the most significant bit in binary number : The decimal number is
1 * 2^7 + 1 * 2^6 + 1 * 2^5 + 1 * 2^4 + 0 * 2^3 + 0 * 2^2 + 1 * 2^1 + 1 * 2^0
= 243
The implemented code would be

int binTodec[8] = {1,1,1,1,0,0,1,1};
int result = 0;

for (int i = 0; i < 8; i++) {
    result *= 2;
    result += binTodec[i];
}
printf("%d\n", result);

On the other hand, if binTodec[0] is the least significant bit in binary number :
The decimal number is
1 * 2^0 + 1 * 2^1 + 1 * 2^2 + 1 * 2^3 + 0 * 2^4 + 0 * 2^5 + 1 * 2^6 + 1 * 2^7
= 207

The implemented code would be

int binTodec[8] = {1,1,1,1,0,0,1,1};
int result = 0;

for (int i = 7; i >= 0; i--) {
    result *= 2;
    result += binTodec[i];
}
printf("%d\n", result);

Upvotes: 1

0___________
0___________

Reputation: 68059

unsigned toUnsigned(const int *arr, size_t size)
{
    unsigned result = 0;

    if(arr && size)
    {
        while(size--)
        {
            result *= 2;
            result += !!*arr++;
        }
    }
    return result;
}

Upvotes: 0

Related Questions