BIN to DEC

closed account (4w7X92yv)
Hello

I looked all over the internet looking for a program that converts a BINARY value (01111100) to a DECIMAL value (124).
Can someone help me whit the code plz?
I don't know how to start

Best Regards
Joriek
Set total to zero.

Start at binary digit on the far right: multiply it by one, add to the total
One to the left: multiply it by two, add to the total
One to the left: multiply it by four, add to the total
One to the left: multiply it by eight, add to the total
One to the left: multiply it by sixteen, add to the total
...
...

and so on until you've done all the binary digits.
closed account (4w7X92yv)
I know how to convert it on paper, but i have to program it, idk how to do that
http://en.wikipedia.org/wiki/Binary_numeral_system#Decimal

Probably the easiest way to do that in C/C++ is treating 1111100 as a string (char array). Like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <string.h>
#include <math.h>

int bin2dec(const char* binary)
{
    int len,dec=0,i,exp;

    len = strlen(binary);
    exp = len-1;

    for(i=0;i<len;i++,exp--)
        dec += binary[i]=='1'?pow(2,exp):0;
    return dec;
}

int main()
{
    printf("%d\n",bin2dec("01111100"));

    return 0;
}


There should be another more efficient way to do this but with this you could have an idea.
Do you know how to get an individual digit from the binary value?
closed account (4w7X92yv)
@moschops no i don't
closed account (4w7X92yv)
@naderST
how can i change it so i can input the value that should be converted?
thanks
Are you kidding? Have you ever made a hello world program on C at least? scanf, gets both functions are used to read from standard input stream. (CONSOLE)
You need to learn some C++ first.

http://www.cplusplus.com/doc/tutorial/
Topic archived. No new replies allowed.