在单个 Java 程序中将一个进制转换为其他进制
假设我们有一个八进制数。要将八进制数转换为其他进制数(如二进制、十六进制等),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("Converting the number from octal to binary: "+ base_convert (my_num, source, destination));
destination = 10;
System.out.println("Converting the number from octal to decimal : "+ base_convert (my_num, source, destination));
destination = 16;
System.out.println("Converting the number from octal to hexadecimal: "+ base_convert (my_num, source, destination));
}
}输出
Converting the number from octal to binary: 11100101 Converting the number from octal to decimal : 229 Converting the number from octal to hexadecimal: e5
定义了一个名为“Demo”的类,其中定义了一个名为“base_convert”的函数。这个函数解析从源进制到目标进制的整数,将其转换为字符串并作为输出返回。在主函数中,定义了数字的值、源进制和不同的目标进制。使用数字、源和目标作为参数调用“base_convert”函数。显示相关输出。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP