| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Please view this simple code and provide any advice as to why the program fails miserably to convert a positive integer to binary. I'm self teaching and thought this simple exercise would be a fun way to start. NOTE: It works for 1 and 2! Yeehaw!
I've manually debugged this program and it seems to work perfectly for various test values. I'm using Microsoft Visual C++ v6.0, Service Pack 6. I can't use the debugger because I'm also running XP and it has problems. I've downloaded the appropriate symbol files but it didn't fix them. I even downloaded the Windows Debugging Tools but those have a problem with the symbol files also. Help! #include <iostream.h> void main() { int Number; cout << "\nPlease enter a positive integer: "; cin >> Number; int Msb_d = 1; //most-significant-bit (decimal value) int Exp = 0; //binary exponent while (Msb_d*2-1 < Number) //while the decimal value of the cumulative sum of binary bits from right to left is less than Number { ++Exp; Msb_d = 2^Exp; } cout << "\n1"; //minimum value of 1 assumed for purposes of this program by "positive integer" specification int Remainder = Number-Msb_d; for (int x=Exp; x>0; --x) { if (Remainder >= (2^x)) { cout << 1; Remainder = Remainder-2^x; } else cout << 0; } cout << endl << endl; } Thanks for any assistance! |
|
#2
|
|||
|
|||
|
Ok as far as I know you can't do a^b you need to call the pow function (pow (a, b)) and use what that returns instead. Also you should give some thought to learning about bitwise operators since they would simplify this task immensely.
For example - Code:
for (int x=0, y=1; x<32 x++, y*=2)
if (number & y)
cout << "1";
else
cout << "0";
What this does is check the value of the number when you mask off each bit and output 0 or 1 corresponding to whether the bit is set or not. Of course it'll always output 32 bits and the bit representation will be backwards but the point is the same. -KM- |
|
#3
|
|||
|
|||
|
Wow, DUH, thanks for the info. Pow helped. I've still got some odd problem with decimal value 50 missing from the binary output for some numbers, but I'll look into it further. Thanks again.
|
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Problem converting integer to binary |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|