将一个数转化为八进制和16进制
时间: 2024-09-29 21:09:59 浏览: 28
将一个十进制整数转换为八进制或十六进制,可以使用内置的转换函数。以下是几种常见的编程语言示例:
1. **Python**:
```python
# 十进制转八进制
decimal_number = 123
octal_number = oct(decimal_number)
print("八进制:", octal_number)
# 十进制转十六进制
hex_number = hex(decimal_number)
print("十六进制:", hex_number)
```
2. **JavaScript**:
```javascript
let decimalNumber = 123;
let octalNumber = parseInt(decimalNumber, 10).toString(8);
let hexadecimalNumber = decimalNumber.toString(16);
console.log("八进制:", octalNumber);
console.log("十六进制:", hexadecimalNumber);
```
3. **Java** (使用`Integer`类的`toOctalString()`和`toHexString()`方法):
```java
int decimalNumber = 123;
String octal = Integer.toOctalString(decimalNumber);
String hexadecimal = Integer.toHexString(decimalNumber);
System.out.println("八进制: " + octal);
System.out.println("十六进制: " + hexadecimal);
```
4. **C++**:
```cpp
#include <iostream>
#include <bitset>
int main() {
int decimalNumber = 123;
std::string octal = std::bitset<32>(decimalNumber).to_string(2); // Java的八进制形式
std::string hexadecimal = std::to_string(decimalNumber, 16);
std::cout << "八进制: " << octal << std::endl;
std::cout << "十六进制: " << hexadecimal << std::endl;
return 0;
}
```
阅读全文