1

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

1
  • What do you need help with? The conversion logic? coding the logic itself? Please clarify Commented Feb 13, 2022 at 12:37

2 Answers 2

1

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

5 Comments

A perfect use case for the downto operator: for (int i = 8; i --> 0;) { ... }
Is that newly invented "downto" operator intented to confuse people learning C?
What if I rewrite the default example to for (int i = 7; i >= 0; i--), and add the downto example at the end as additional footnote?
Using --> is not a problem. But calling is an operator confuses people. Beginners might believe that it actually is an operator. Which it is not. It is just a post decrement operator followed by a larger than operator
It makes sense. I will revert my answer to the original version. Because it has a similar pattern of the other case, and it's easier to understand. Explaining the combination of 2 operators would be a further topic of this question.
0
unsigned toUnsigned(const int *arr, size_t size)
{
    unsigned result = 0;

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

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.