将十进制转化为二进制用C++实现
时间: 2024-11-09 12:25:48 浏览: 24
十进制转换二进制(原码)
在C++中将十进制转换为二进制可以使用内置库函数`bitset`,或者手动通过循环除以2并取余数的方式来实现。这里我会展示两种方法:
1. **使用bitset**:
```cpp
#include <bitset>
#include <iostream>
std::string decimalToBinary(int decimal) {
std::bitset<32> binary(decimal); // 使用32位bitset来存储,实际需要根据decimal的最大值调整
return binary.to_string();
}
int main() {
int number = 42;
std::cout << "Binary representation of " << number << " is: " << decimalToBinary(number) << std::endl;
return 0;
}
```
2. **手动计算** (Long Division Algorithm):
```cpp
#include <iostream>
#include <string>
std::string decimalToBinaryManually(int decimal) {
std::string binary = "";
while (decimal > 0) {
binary = std::to_string(decimal % 2) + binary;
decimal /= 2;
}
return binary;
}
int main() {
int number = 42;
std::cout << "Binary representation of " << number << " is: " << decimalToBinaryManually(number) << std::endl;
return 0;
}
```
阅读全文