Hello all, I wrote a program that converts a decimal (base 10) number to binary (base 2). It works perfectly fine, but I'm just wondering if there is a simpler way of doing it....?
Yes, there is a much more elegant way of doing it. Try doing this on paper: write down any number. If it is even, write a 0 to the right. If it is odd, write a 1 to the side. Then, divide it by 2 and round down and write the result below the number. Keep repeating this process until you get to 0. Then, read the 0s and 1s on the right from bottom to top to get your binary number.
This works for converting to any base from any base - the numbers on the right are just the remainder of division.
There's also the "easy way" out, where you just use a std::bitset<sizeof(int)*CHAR_BIT> to store the integer and then just print that out (or use the to_string member function if you want it in string form).
Of course, that's not any fun, now, is it? :)
(In particular, it doesn't really teach you much about binary numbers and/or base conversions, so if that's what you were going for, then...)