进制转化代码
时间: 2025-05-12 08:40:07 浏览: 19
### C语言实现进制转换
在C语言中,可以通过编写自定义算法来完成不同进制之间的转换。下面是一个完整的代码示例,展示如何将十进制数分别转换为二进制、八进制和十六进制。
#### 十进制到其他进制的转换
```c
#include <stdio.h>
#include <string.h>
void decToBin(int n) {
char binaryNum[32];
int i = 0;
while (n > 0) {
binaryNum[i] = (n % 2) + '0';
n /= 2;
i++;
}
binaryNum[i] = '\0'; // Null terminate the string
strrev(binaryNum);
printf("Binary: %s\n", binaryNum);
}
void decToOctal(int n) {
char octalNum[32];
int i = 0;
while (n > 0) {
octalNum[i] = (n % 8) + '0';
n /= 8;
i++;
}
octalNum[i] = '\0'; // Null terminate the string
strrev(octalNum);
printf("Octal: %s\n", octalNum);
}
void decToHex(int n) {
char hexaDeciNum[100];
int i = 0;
while(n!=0){
int temp = 0;
temp = n % 16;
if(temp < 10){
hexaDeciNum[i] = temp + 48;
i++;
}
else{
hexaDeciNum[i] = temp + 55;
i++;
}
n = n/16;
}
hexaDeciNum[i] = '\0';
strrev(hexaDeciNum);
printf("Hexadecimal: %s\n",hexaDeciNum);
}
int main(){
int num;
printf("Enter a decimal number: ");
scanf("%d",&num);
decToBin(num);
decToOctal(num);
decToHex(num);
return 0;
}
```
上述程序展示了如何将一个给定的十进制整数 `num` 转换为二进制、八进制以及十六进制表示形式[^3]。
---
### Python 实现进制转换
Python 提供了内置函数可以直接用于进制间的相互转换。以下是一段简单的代码示例:
```python
def convert_bases(number):
binary_representation = bin(number)[2:] # 去掉前缀'0b'
octal_representation = oct(number)[2:] # 去掉前缀'0o'
hexadecimal_representation = hex(number)[2:].upper() # 去掉前缀'0x'
print(f"Decimal: {number}")
print(f"Binary: {binary_representation}")
print(f"Octal: {octal_representation}")
print(f"Hexadecimal: {hexadecimal_representation}")
if __name__ == "__main__":
try:
user_input = int(input("Please enter a decimal number: "))
convert_bases(user_input)
except ValueError:
print("Invalid input! Please provide an integer.")
```
此脚本允许用户输入任意正整数值并打印其对应的二进制、八进制及十六进制表达方式[^4]。
---
### Java 中的进制转换
对于Java而言,可以利用标准库中的工具简化操作过程。这里给出一段基于命令行交互的小型应用实例:
```java
import java.util.Scanner;
public class BaseConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a decimal value:");
String inputValue = scanner.nextLine();
try {
int decimalValue = Integer.parseInt(inputValue, 10);
String binaryString = Integer.toBinaryString(decimalValue);
String octalString = Integer.toOctalString(decimalValue);
String hexString = Integer.toHexString(decimalValue).toUpperCase();
System.out.println("Binary:" + binaryString);
System.out.println("Octal:" + octalString);
System.out.println("Hexadecimal:" + hexString);
} catch(NumberFormatException e){
System.err.println("Error parsing your entry as base-10 integer.");
}
scanner.close();
}
}
```
以上片段实现了从控制台读取数据,并调用相应的方法执行必要的计算工作流[^2]。
---
阅读全文
相关推荐

















