สมมุติว่าเรามีเลขฐานแปด ในการแปลงเลขฐานแปดเป็นฐานอื่น เช่น เลขฐานสอง เลขฐานสิบหก เป็นต้น โค้ด 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' ถูกเรียกด้วยตัวเลข ต้นทาง และปลายทางเป็นพารามิเตอร์ ผลลัพธ์ที่เกี่ยวข้องจะปรากฏขึ้น