How do i print out on the screen the binary representation of an arbitrary unsigned integer?
How do i print out on the screen the binary representation of an arbitrary unsigned integer?
You'd have to write a function to convert it yourself. Unfortunately, <iomanip> provides no manipulators to convert to binary, they do have manipulators for hexadecimal and octal.
Here is a sloppy little binary convert I quickly wrote up. With any thought it could be done better, but it works. Logically, I'm sure some use of bitwise operators would yield the best result.Code:// Binary converter -- Output is a std::string #include <iostream> #include <string> std::string binForm(std::string binNum) { // Puts proper spaces between every 4 bits int strLen = binNum.size(); while(strLen - 4 > 0) { binNum.insert((strLen -= 4), " "); } return binNum; } std::string binary(unsigned long deciNum) { std::string binNum; unsigned long currBit = 1; while(currBit * 2 <= deciNum) // Find the highest true bit in the number currBit *= 2; do { // Go through each bit checking if it's 1 or 0 if (deciNum >= currBit) { deciNum -= currBit; binNum += "1"; } else binNum += "0"; currBit /= 2; } while(currBit != 0); return binForm(binNum); } int main() { std::cout << "8 in binary is " << binary(8) << '\n' << "14 in binary is " << binary(14) << '\n' << "122 in binary is " << binary(122) << '\n' << "488 in binary is " << binary(488) << std::endl; std::cin.get(); return 0; }
Last edited by SlyMaelstrom; 06-10-2006 at 01:20 AM.
Sent from my iPadŽ
Thanks a lot man!
Nice bit of spoon feeding there - did you learn anything without ever having tried it yourself?
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Yeah, I admittedly did spoon feed him, but I did it because it would have quite simply taken just as long to explain the conversion from decimal to binary.
To the OP. You really, really should take a hard look at what's going on in that code. Also there are plenty of resources on the internet that teaches the basics of the binary number system. You won't get very far in the programming world without knowing it, so do yourself a favor if you haven't already and learn it.
Oh and... via bitwise operation, if anyone wants to check how much quicker it is:Code:std::string binary(unsigned long deciNum) { std::string binNum; unsigned long currBit = 1; while((currBit << 1) <= deciNum) // Find the highest true bit in the number currBit <<= 1; do { // Go through each bit checking if it's 1 or 0 if (deciNum & currBit) binNum += "1"; else binNum += "0"; currBit >>= 1; } while(currBit != 0); return binForm(binNum); }
Last edited by SlyMaelstrom; 06-10-2006 at 03:20 AM.
Sent from my iPadŽ