I'm trying to create a simple program to convert a binary number, for example 111100010
to decimal 482
. I've done the same in Python, and it works, but I can't find what I'm doing wrong in C++.
When I execute the C++ program, I get -320505788
. What have I done wrong?
This is the Python code:
def digit_count(bit_number):
found = False
count = 0
while not found:
division = bit_number / (10 ** count)
if division < 1:
found = True
else:
count += 1
return count
def bin_to_number(bit_number):
digits = digit_count(bit_number)
number = 0
for i in range(digits):
exp = 10 ** i
if exp < 10:
digit = int(bit_number % 10)
digit = digit * (2 ** i)
number += digit
else:
digit = int(bit_number / exp % 10)
digit = digit * (2 ** i)
number += digit
print(number)
return number
bin_to_convert = 111100010
bin_to_number(bin_to_convert)
# returns 482
This is the C++ code:
#include <iostream>
#include <cmath>
using namespace std;
int int_length(int bin_number);
int bin_to_int(int bin_number);
int main()
{
cout << bin_to_int(111100010) << endl;
return 0;
}
int int_length(int bin_number){
bool found = false;
int digit_count = 0;
while(!found){
int division = bin_number / pow(10, digit_count);
if(division < 1){
found = true;
}
else{
digit_count++;
}
}
return digit_count;
}
int bin_to_int(int bin_number){
int number_length = int_length(bin_number);
int number = 0;
for(int i = 0; i < number_length; i++){
int e = pow(10, i);
int digit;
if(e < 10){
digit = bin_number % 10;
digit = digit * pow(2, i);
number = number + digit;
}
else{
if((e % 10) == 0){
digit = 0;
}
else{
digit = bin_number / (e % 10);
}
digit = digit * pow(2, i);
number = number + digit;
}
}
return number;
}