十进制转二进制八进制十进制C++
时间: 2024-10-31 12:08:24 浏览: 8
在C++中,你可以使用内置函数或者自定义算法来进行十进制数到二进制、八进制和十六进制的转换。以下是简单的例子:
**将十进制转换为二进制:**
```cpp
#include <bitset>
#include <iostream>
int main() {
int decimal = 42;
std::string binary = std::bitset<8>(decimal).to_string(); // 使用std::bitset的to_string方法,自动填充0
std::cout << "Decimal to Binary: " << decimal << " in binary is " << binary << std::endl;
return 0;
}
```
**将十进制转换为八进制:**
```cpp
#include <iostream>
#include <iomanip>
int main() {
int decimal = 42;
std::string octal = std::oct << decimal; // C++11以后,可以使用std::oct前缀直接转换
std::cout << "Decimal to Octal: " << decimal << " in octal is " << octal << std::endl;
return 0;
}
```
**将十进制转换为十六进制:**
```cpp
#include <iostream>
#include <hex>
int main() {
int decimal = 42;
std::string hexadecimal = std::hex << decimal; // 使用std::hex前缀直接转换
std::cout << "Decimal to Hexadecimal: " << decimal << " in hex is " << hexadecimal << std::endl;
return 0;
}
```
阅读全文