十进制转为二进制和八进制和十六进制的代码
时间: 2024-11-30 18:17:39 浏览: 19
将十进制转换成二进制、八进制和十六进制通常涉及基本的算数操作或位操作。以下是几种常见的编程语言中如何进行这种转换的例子:
**Python:**
```python
def decimal_to_binary(dec):
binary = bin(dec)[2:] # Python内置bin()函数生成二进制,去掉前缀"0b"
return binary
def decimal_to_octal(dec):
octal = oct(dec)[2:] # Octal用oct()函数,去掉前缀"0o"
return octal
def decimal_to_hexadecimal(dec):
hexadecimal = hex(dec)[2:].upper() # Hex用hex()函数,去掉前缀"0x"并转换为大写
return hexadecimal
# 使用示例
decimal_number = 42
binary = decimal_to_binary(decimal_number)
octal = decimal_to_octal(decimal_number)
hexadecimal = decimal_to_hexadecimal(decimal_number)
print(f"{decimal_number} in binary is {binary}, in octal is {octal}, and in hexadecimal is {hexadecimal}.")
```
**JavaScript:**
```javascript
function decimalToBinary(dec) {
return dec.toString(2);
}
function decimalToOctal(dec) {
return dec.toString(8);
}
function decimalToHexadecimal(dec) {
return dec.toString(16).toUpperCase();
}
// 使用示例
let decimalNumber = 42;
const binary = decimalToBinary(decimalNumber);
const octal = decimalToOctal(decimalNumber);
const hexadecimal = decimalToHexadecimal(decimalNumber);
console.log(`${decimalNumber} in binary is ${binary}, in octal is ${octal}, and in hexadecimal is ${hexadecimal}.`);
```
阅读全文