简体   繁体   中英

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

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);
unsigned toUnsigned(const int *arr, size_t size)
{
    unsigned result = 0;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM