binary to decimal and decimal to binary functions

Sinaru 1 Tallied Votes 183 Views Share

I wrote this code for fun. Wanted to do such a thing so that I would be able to use this in the future. I'm kinda new to this forum. I like to know what you think about the code. If can point out some mistakes or ways to improve the code, it would be great.. :)

The ICE Man commented: Well Done :) +0
#include <iostream>
#include <math.h>
using namespace std;

/* The following function coverts a binary value to an int value. You have to
 * input the binary value as a string to this function and then it will output
 * the int number of it. Characters other than 0 will treat as a 1 or true.
 */
int bin2dec(string binVal)
{
    int total = 0;
    int i=0;
    int length = binVal.length();
    int isMinus= false;

    if(binVal[0] == '-')
    {
        isMinus = true;
        length--;
        for(i=0; i<length;i++)
        {
            binVal[i] = binVal[i+1];
        }
    }

    for (i=0; i < length; i++)
    {

        if (binVal[length - (i + 1)] != '0')
            total = total + pow(2, i);
    }

    if(isMinus)
        total = total * (-1);

    return total;
}

/* The Following function can be used to convert an integral value to binary.
 * Provide the integral value to this function and it will output the related
 * binary value in a string format.
 */
string dec2bin(int decVal)
{
    string value = "";

    bool isMinus = false;

    if (decVal < 0)
    {
        isMinus = true;
        decVal = decVal * (-1);
    }

    while (decVal > 0)
    {
        if (decVal % 2)
            value = '1' + value;
        else
            value = '0' + value;

        decVal = decVal / 2;
    }

    if (isMinus)
        value = '-' + value;

    return value;
scott_dabas -2 Newbie Poster

code is good but for decimal to binary conversion, it can get even better ........ multiply the remainders with powers of 10 from 0 onwards ....after dividing the dec number by 2 like we do while converting binary to dec.
the code gets even simpler for dec to binary conversion.

mbulow 10 Junior Poster in Training

Hi Sinaru :-)

Since I don't know how familiar you are with stuff like this I have too ask:

You represent a negative binary number as a positive binary number prefixed with a '-'. Is that your own intentional design or because you do not know the real way to represent negative numbers?

Sinaru 0 Newbie Poster

Sorry for the delayed answer. I'm currently working on our final software project for the HND.

@mbulow: I used the - sign so that the common users would understand that it's a negative value. I didn't try to convert it into the way that computers hold the negative values.

@scott: Thnx for the info.. I will see about that.. :)

BTW I found a bug when converting dec2bin. That is if you password 0 as the integer value, the return value will be nothing. So I used another (else)if statement before the while loop to see if the int value is 0 and if it is then returns 0... :P

mrnutty 761 Senior Poster

Here is a way to do it using metaprograming. That way you get the result before you
even start the program.

#include <iostream>


template<int binarySequence>
struct Binary{
	enum{ result = Binary<binarySequence/10>::result << 1 | binarySequence % 10 };
};
template<>
struct Binary<0>{
	enum{ result = 0 };
};

int main(){		
	using namespace std;
	cout << Binary<1>::result << endl; // outputs 2^0
	cout << Binary<10>::result << endl; // outputs 2^1
	cout << Binary<100>::result << endl; // outputs 2^2
	cout << Binary<1000>::result << endl; // outputs 2^3
	cout << Binary<10000>::result << endl; // outputs 2^4
	cout << Binary<10100>::result << endl; // outputs 20

}

I admit, that the formula used is not credited to me. Although the above works.
It does not have a error checking, for input that does not consists of 1's and 0's.

Isn't this so cool? You get the answer before you even run your program!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.