A
Al
I am typing the following code to convert a binary number to decimal.
It usually works fine, but with some numbers, it reads strange values:
#include <iostream>
using namespace std;
int main()
{
int binar;
cin >> binar;
// cout <<binar <<endl;
int dec=0, num=1;
dec += (binar%10) * 1;
binar /= 10;
while (binar>1)
{
dec += (binar%10) * num*2;
num*=2;
binar /= 10;
}
dec += binar * num*2;
cout << dec <<endl;
system("pause");
return 0;
}
when I debug or I use the comment line with a value: 10011001100, it
prints (the value of binar is) 2 and the decimal is also 2.
Same problem with the following code in C, but the values are a lot
different: 1421066508 for binar value and 2028 for dec:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int bin, dec=0, num=1;
scanf("%d", &bin);
printf("%d\n", bin);
dec += (bin%10) * 1;
bin /= 10;
while (bin>1)
{
dec += (bin%10) * num*2;
num*=2;
bin /= 10;
}
dec += bin * num*2;
printf("%d\n", dec);
system("pause");
return 0;
}
do you know what the problem is??
is it for overflow of integer?
help!
It usually works fine, but with some numbers, it reads strange values:
#include <iostream>
using namespace std;
int main()
{
int binar;
cin >> binar;
// cout <<binar <<endl;
int dec=0, num=1;
dec += (binar%10) * 1;
binar /= 10;
while (binar>1)
{
dec += (binar%10) * num*2;
num*=2;
binar /= 10;
}
dec += binar * num*2;
cout << dec <<endl;
system("pause");
return 0;
}
when I debug or I use the comment line with a value: 10011001100, it
prints (the value of binar is) 2 and the decimal is also 2.
Same problem with the following code in C, but the values are a lot
different: 1421066508 for binar value and 2028 for dec:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int bin, dec=0, num=1;
scanf("%d", &bin);
printf("%d\n", bin);
dec += (bin%10) * 1;
bin /= 10;
while (bin>1)
{
dec += (bin%10) * num*2;
num*=2;
bin /= 10;
}
dec += bin * num*2;
printf("%d\n", dec);
system("pause");
return 0;
}
do you know what the problem is??
is it for overflow of integer?
help!