In C++, common methods for converting decimal numbers to binary include using bitwise operations or the more intuitive division-by-2 method. Below, I will explain both methods in detail and provide code examples.
Method 1: Using Bitwise Operations (Bit Shift and Bitwise AND)
This method uses bitwise operations to directly extract binary digits from an integer. The specific steps are as follows:
- Determine whether each bit of the integer is 1, starting from the most significant bit to the least significant bit.
- Use bitwise AND (&) and bitwise shift (>>) operations to check each bit.
The following is a C++ code example:
cpp#include <iostream> #include <bitset> // For outputting binary form void printBinary(int num) { for (int i = 31; i >= 0; i--) { int k = num >> i; if (k & 1) std::cout << "1"; else std::cout << "0"; } } int main() { int number = 9; std::cout << "Binary form: "; printBinary(number); std::cout << "\n"; return 0; }
In this code, we shift the integer right by i bits and perform a bitwise AND with 1 to check if the least significant bit is 0 or 1, then output the corresponding result.
Method 2: Division-by-2 Method
This method repeatedly divides the number by 2 and records the remainders, then reverses the recorded remainders to obtain the binary representation. The specific steps are as follows:
- Divide the number by 2.
- Record the remainder.
- Take the quotient as the new number.
- Repeat the above steps until the number becomes 0.
- Reverse the recorded remainders to obtain the binary representation.
The following is a C++ code example:
cpp#include <iostream> #include <string> #include <algorithm> // For reverse function std::string decimalToBinary(int num) { std::string result; while (num > 0) { result += (num % 2 == 0 ? "0" : "1"); num /= 2; } reverse(result.begin(), result.end()); // Reverse the string return result; } int main() { int number = 9; std::cout << "Binary form: " << decimalToBinary(number) << "\n"; return 0; }
In this code, we repeatedly divide the number by 2 and record the remainders, then use the std::reverse function to reverse the string to obtain the correct binary representation.
Both methods can effectively convert decimal numbers to binary. The choice depends on the specific application context and personal preference. Bitwise operations are typically more efficient, but the division-by-2 method may be more straightforward and easier to understand logically.