在单个 Java 程序中将一个基数转换为其他基数
javaobject oriented programmingprogramming更新于 2025/7/23 3:56:17
假设我们有一个八进制数。要将八进制转换为其他基数(如二进制、十六进制等),Java 代码如下 −
示例
public class Demo{
public static String base_convert(String num, int source, int destination){
return Integer.toString(Integer.parseInt(num, source), destination);
}
public static void main(String[] args){
String my_num = "345";
int source = 8;
int destination = 2;
System.out.println("将数字从八进制转换为二进制:"+ base_convert (my_num, source, destination));
destination = 10;
System.out.println("将数字从八进制转换为十进制:"+ base_convert (my_num, source, destination));
destination = 16;
System.out.println("将数字从八进制转换为十六进制:"+ base_convert (my_num, source, destination));
}
}
输出
将数字从八进制转换为二进制:11100101 将数字从八进制转换为十进制:229 将数字从八进制转换为十六进制:e5
名为 Demo 的类包含一个名为 ‘base_convert’ 的函数。此函数将整数从源进制解析到目标进制,将其转换为字符串并将其作为输出返回。在主函数中,定义了数字、源进制和不同目标进制的值。‘base_convert’函数被调用,参数为数字、源和目标。显示相关输出。
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

