Computer >> Máy Tính >  >> Lập trình >> Java

Chuyển đổi một cơ sở sang các cơ sở khác trong một chương trình Java duy nhất

Giả sử chúng ta có một số Bát phân. Để chuyển đổi hệ bát phân sang các cơ số khác như nhị phân, thập lục phân, v.v., mã Java như sau -

Ví dụ

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));
   }
}

Đầu ra

Converting the number from octal to binary: 11100101
Converting the number from octal to decimal : 229
Converting the number from octal to hexadecimal: e5

Một lớp có tên Demo chứa một hàm có tên là ‘base_convert’ được định nghĩa. Hàm này phân tích cú pháp số nguyên từ cơ sở nguồn đến cơ sở đích, chuyển đổi nó thành một chuỗi và trả về nó dưới dạng đầu ra. Trong hàm chính, giá trị cho số, cho cơ sở nguồn và cho các cơ sở đích khác nhau được xác định. Hàm ‘base_convert’ được gọi với tham số là số, nguồn và đích. Đầu ra có liên quan được hiển thị.