|
-
October 7th, 2007, 07:59 PM
#1
binary calculation overflow?
I had to write a binary to decimal conversion program for a exercise in a c++ book.
My program works fine, but it seems to be running out of memory space for the variable. If i use "int" to declare my variables the program will work fine up to an output of 1024. I tried even declaring as __int64 and the code will output correctly up to 524XXX (19bit).
edit: guess i should make it clear how entering a 16bit binary for instance will not output correctly as 65535 when variables are declared "int". It output instead to some garbage of 186 or something. I have to declare variables to __int32 to output 16bit and _int64 outputs up to around 19bit
this doesnt seem right..
does my code seem ok?
Code:
#include <iostream>
using namespace std;
int main()
{
__int64 binary;
__int64 total = 0;
cout << "Enter binary number: ";
cin >> binary;
for ( int count = 1;binary != 0;count *= 2)
{
if ( binary == 1 )
{
total += count;
binary = 0;
break;
}
if ( binary % 2 )
total += count;
binary /= 10;
}
cout << "\nDecimal equivilant is: " << total << endl;
cout << "\n\n";
system("PAUSE");
return 0;
}
Last edited by #Christopher#; October 7th, 2007 at 08:54 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|