Home > Mobile >  How to convert binary array to decimal in C
How to convert binary array to decimal in C

Time:02-14

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

CodePudding user response:

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

Thank for @chqrlie's suggestion about downto operator:

In the case which binTodec[0] is the least significant bit, we can also traverse from binTodec[7] to binTodec[0], via combining -- operator and > operator together in a single condition statement:

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

/* another method to traverse from binTodec[7] to binTodec[0] */
for (int i = 8; (i--) > 0;) {
    result *= 2;
    result  = binTodec[i];
}
printf("%d\n", result);

CodePudding user response:

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

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