So we have to convert dec into bin oct and hex. The bin has to use a while loop and right now mine is in an infinite loop. I thought that doing 'bin++' adds 1 to the variable so this does not happen?
Also to convert decimal to binary, don't you find the modulus of the number then divide it by 2??? - It doesn't seem to be working.
I'm so confused, i'm not even a computer science major, i'm graphic design and I wanted to learn a bit of programming (like c++) so I know what developers are doing to make the apps I design (front-end) work.
Can someone explain in lay-man's terms whats going on? I think I get the whole concept of the loops and everything it's just implementing them is difficult. My book is just saying the same thing over and over; 'while (expression) statement;'
* Also, sorry if the code isn't formatted, I didn't know if copy/paste is all I need to do*
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int low;
int high;
int a;
int bin2;
cout << "Enter the low number: ";
cin >> low;
cout << "Enter the high number: ";
cin >> high;
cout << "Decimal Binary Octal Hexadecimal" << endl;
for (a = low; a <= high; a++)
{
cout << a << "\t" << endl;
}
int bin = low;
while (bin <= high)
{
bin = low % 2;
low /= 2;
bin2 = low;
cout << bin2 << "\t" << endl;
bin++;
}
return 0;
The other problem is the nasty bit that you're extracting the least significant binary digit first, but you want to print that one last. You can handle this easily with a simple C char array and fill it in backwards:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
string toBinary(unsignedint num)
{
char buf[30];
buf[29] = 0;
char *cp = buf+29;
if (num == 0) return"0"; // special case for zero.
while (num) {
--cp;
int digit = num%2; // get the least significant digit
*cp = '0' + digit; // digit 0 -> character '0'. Digit 1 -> character '1'
num /= 2;
}
return cp;
}
Line 15 converts the C string to a std::string and returns it.