```
#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;
```

Recommended Topics