For a little challenge exercise i was doing i had to come up with a program that would take a decimal number as input and output it in binary form (ie 36 = 100100). I was successful in doing this, but only with a long, complicated program that mathematically converted them. I figure since everything in a computer's memory is in binary anyway, there should be a much easier way to just tell it to print the raw binary value of the integer variable. Is there such a way?
BTW, here is the long, complicated (but working none-the-less) method that i came up with:
OK so I just put that in cuz its the first program i've ever written longer than 10 or so lines and i was pretty proud of myselfCode:#include <iostream> #include <cstring> using namespace std; float pwr(int b, int e); int main() { float value, remainder; int largest_digit, power; bool done = 0; char in_binary[255]; cout << "Enter the number: \n"; cin >> value; cin.ignore(); for (int x = 0; done == 0; x++) { if ((value / pwr(2, x)) < 2) { largest_digit = x; done = 1; } } done = 0; remainder = value; power = largest_digit; for (int x = 0; power >= 0; x++) { if ((remainder / pwr(2, power)) >= 1) { in_binary[x] = '1'; remainder = (remainder - pwr(2, power)); } else { in_binary[x] = '0'; } power = (power - 1); } in_binary[(largest_digit + 1)] = '\0'; cout << "\n" << in_binary << "\n"; system("pause"); } float pwr(int b, int e) { if (e != 0) { int n; n = b; for (int x = 0; x < (e - 1); x++) { n = (n * b); } return float(n); } else { return 1; } }