在單個 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