binary to decimal

hi friends!.

I am beginer c++ programmer and i have problem with converting binary to decimal.
please give me easiest code to converting .
thanx

Last edited on
Use std::bitset to present the binary number. Then just use the std::bitset::to_ulong() member function to get the decimal value.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
#include <bitset>
 
int main()
{
	std::string s("100"); // 100 in binary is 4 in decimal
	// Note: You have to specify exactly how many bits you need
	std::bitset<sizeof(int) * 8> b(s);
	std::cout << b.to_ulong() << '\n';
	return 0;
}


Or have a look at the C function itoa(), but have in mind that it's non-standard, which means that not every implementation supports it.

http://www.cplusplus.com/reference/cstdlib/itoa/
Last edited on
thanks a lot
but I've compiled the code with borland c++
But I saw this error:

Error: noname02.cpp(10,11):'cout' is not a member of 'std'

thanks again.
closed account (jvqpDjzh)
I have created this function that should work, but it takes a string as binary number:
//returns -1 if the string is empty or the string contains other digits (chars) than 0 or 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
long BinaryToDecimal(std::string bits)
{
    if(bits != "")
    {
        int decimal = 0;
        for(int i = (bits.length() - 1), j = 0; i >=0 && j<bits.length(); i--, j++)
        {
            switch(bits.at(j))
            {
            case '1':
                decimal += pow(2, i);
                break;
            case '0':
                break;
            default:
                decimal = -1;
                break;
            }
          if(decimal == -1)break;
        }
          return decimal;
    }
    return -1;
}


EDIT: You have at least to know how to convert mathematically a binary number to a decimal one ;)

EDIT: I have changed something: i had written this function when I was tired and I forgot one thing, but now it's returning -1, if it can't convert the string representing the binary number to the decimal one (because the string contains other digits than 1 or 0)
Last edited on
thanks zwilu but i compile this and there is a syntax error in line 3 and i cant fix it
Last edited on
closed account (jvqpDjzh)
Have you included <string> for using the string class and <cmath> (for pow()) headers?
Last edited on
oh i forget it !
i'm tired too ! ;)
Last edited on
Topic archived. No new replies allowed.