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.. :)
binary to decimal and decimal to binary functions
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
mbulow 10 Junior Poster in Training
Sinaru 0 Newbie Poster
mrnutty 761 Senior Poster
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.