How to convert binary to decimal?

Asked

Viewed 12,313 times

11

I had to make a huge equation to convert a binary number to decimal.

What is the best way to make such a conversion?

For example

0011 1011 0101 = 949

At the suggestion of Jorge B., I am putting my conversion attempt, just for illustration, it is not necessary to correct/take seriously, it is just illustrative, .

temp3 =   
    (listReport.numberBaseA*2)*(listReport.numberBaseA*2)*(listReport.numberBaseA*2)+ 
    (listReport.numberBaseB*2)*(listReport.numberBaseB*2) + 
    (listReport.numberBaseC*2) + 
    (listReport.numberBaseD) 
;

Well, that was just for 4 bits, my conversions need 24 bits, so imagine the size...

I’m studying this code provided by Bacco, I’m catching peace! but I’m firm and strong studying it!

#include<stdio.h>
#include<string.h>
#include<math.h>

int main()
{
    char bin[100];
    int dec = 0;
    int i = 0;
    int s;
    fgets( bin, sizeof(bin), stdin);
    s = strlen( bin );
    while( s-- ) dec = dec + pow(2, i++) * (bin[s] - 48);
    printf("\nDecimal Equivalent of Binary Number: \t %d\n", dec);
    return 0;
}
  • 2

    But you know how to convert by hand? You tried something?

  • Yes. At the moment I wrote a function full of variables! rsrsr became horrible! and big, but it does not miss the value! But I need to learn the right way!

  • 3

    Oh that’s very good, don’t you want to add your function to improve the content of the question? So they can even help you in what you may have done wrong, we do code review here ;)

  • I added! it is not worth giving laughed of my beginner code... rsrs

  • 1

    With this code you cannot put any characters other than zero and one (not even line breaks). I updated the answer with a protection for these cases, and a type that supports up to 4 bytes. But the original algorithm is also right.

  • cool! to studying! : D !

Show 1 more comment

2 answers

10


In Sozão has this very simple code:

#include<stdlib.h>
#include<stdio.h>
#include<math.h>

int main()
{
    int bin, dec = 0, i;
    printf("\nEnter A Binary Number: \t");
    scanf("%d", &bin);
    for(i = 0; bin > 0; i++)
    {
        dec = dec + pow(2, i) * (bin % 10);
        bin = bin / 10;
    }
    printf("\nDecimal Equivalent of Binary Number: \t %d\n", dec);
    return 0;
}

See working on IDEONE.

The same code, adapted to read from strings, for you to test with larger numbers:

#include<stdio.h>
#include<string.h>
#include<math.h>

int main()
{
    char bin[100];
    unsigned long dec = 0;
    int i = 0;
    int s;
    fgets( bin, sizeof(bin), stdin);
    s = strlen( bin );
    while( s-- ) {
        if( bin[s] == '0' || bin[s] == '1' ) {
            dec = dec + pow(2, i++) * (bin[s] - '0');
        }
    };
    printf("\nDecimal Equivalent of Binary Number: \t %u\n", dec);
    return 0;
}

See working on IDEONE.

Original:

https://stackoverflow.com/a/39218420/916193

4

The best way

The best way is to create a code that does this. C has only the basics. C is not C# or Java.

You can look for a library that does this, but there’s nothing that everyone uses and is considered "almost official". It is very common for C programmers to create their own library for these things and leave only complex problems for libraries.

Depiction

Note that people often confuse data with data representation. The number is the number. You don’t see the number, it just exists. What you see is a representation. And to see, it’s certainly a text (string) with numerical digits.

So if there’s a number in memory that’s equivalent to what we know as the 129 to show on the screen we’re going to have to find the character 1, then the 2 and then the 9. As if we are going to show in binary we will find a text 10000001. And hexadecimal 81. Obviously a representation can be stored as well. But it is always text. The secret is to find the correct characters. One does this with pure mathematics. Alias, who has proper mathematical understanding produces simple algorithms for simple problems. And I’m not talking about memorizing formulas. Actually, whoever does this doesn’t learn to solve problems.

I consider it a mistake to work with numerical values to represent data, but I see many exercises like this.

Algorithm

The common exercise of doing this is great for developing ability to produce good algorithms.

The best solution is to divide or multiply the number by the base. Example:

If you have a binary number, how do you calculate it to decimal? From right to left it will always be worth 0 or a value, when it appears 1, according to the position, equal is the decimal.

Let’s look at the decimal that we’re used to. We start from the right which is the least significant value. I could start on the left, but then I’d have to figure out how many digits you have before you start.

Then the last digit is worth its same value. Generically speaking is the value of it times 10 (base) raised to position. In this case the position is zero (remember that we always start from scratch). When I taught classes I felt like crying when the students didn’t know that 10 raising to zero is 1. Math teachers say it’s a convention. But this exercise helps to understand why this "convention" is. The result is stored somewhere. On paper or in computer memory, it depends on where you’re doing the algorithm. If the digit was 5, then we have 5 as a result.

Then we go to the next digit. Again its value is multiplied by the base raised to the position. Now the position is 1. Then 10 1 is 10. So if the digit was 3, then we have 30 as a result.

Then we use digit 6 (for example) times 10 to 2 (next position. So that’s 600.

To do otherwise we trade multiplication for division.

If it only had those digits, we add it all up and it’s 635. That’s how one printf() or a toString() (the formatting function actually) in other languages do to turn the number into representation, or take the representation and generate a number (Parsing, what the scanf() usually do).

The binary only changes the basis, the algorithm is the same. So come on:

0011 1011 0101 from right to left:

1 X 2^0 (1) = 1
0 X 2^1 (2) = 0
1 X 2^2 (4) = 4
0 X 2^3 (8) = 0
1 X 2^4 (16) = 16
1 X 2^5 (32) = 32
0 X 2^6 (64) = 0
1 X 2^7 (128) = 128
1 X 2^8 (256) = 256
1 X 2^9 (512) = 512

Sum all 949.

Now take 949 and do it backwards:

949 % 2 = 1 -> 949 / 2 = 474
474 % 2 = 0 -> 474 / 2 = 237
237 % 2 = 1 -> 237 / 2 = 118
118 % 2 = 0 -> 118 / 2 = 59
59 % 2 = 1 -> 59 / 2 = 29
29 % 2 = 1 -> 29 / 2 = 14
14 % 2 = 0 -> 14 / 2 = 7
7 % 2 = 1 -> 7 / 2 = 3
3 % 2 = 1 -> 3 / 2 = 1
1 % 2 = 1 -> 1 / 2 = 0

It gathers all the remains in reverse: 1110110101

For hexadecimal the base is 16, but the algorithm is the same, on both sides. You can convert even from binary to hexadecimal and vice versa, all direct without passing through decimal.

That’s basically it. Now just encode it. Or get it done.

Completion

The problem is common: /search?q=%5Bc%5D+bin%C3%A1rio+decimal Making huge is optional. The problem is simple and requires a simple solution, and short. Only here on the site has been asked several times.

  • thanks! for people who are starting, knowing this kind of information is all that was missing in school! thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.