Java
 Computer >> コンピューター >  >> プログラミング >> Java

単一のJavaプログラムで1つのベースを他のベースに変換する


8進数があるとしましょう。 8進数を2進数、16進数などの他の基数に変換するには、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」という名前の関数が定義されています。この関数は、整数をソースベースからデスティネーションベースに解析し、文字列に変換して出力として返します。 main関数では、数値、ソースベース、およびさまざまな宛先ベースの値が定義されています。 「base_convert」関数は、番号、送信元、宛先をパラメータとして呼び出されます。関連する出力が表示されます。


  1. 平行四辺形の領域を見つけるJavaプログラム

    この記事では、平行四辺形の面積を見つける方法を理解します。平行四辺形には、2対の平行な等しい反対側があります。ベースと、ベースとその反対側の平行な側との間の垂直距離である高さがあります。 平行四辺形の面積は、式-を使用して計算されます。 base * height i.e. b x h 以下は同じのデモンストレーションです- 入力 入力が-であると仮定します Base : 6 Height : 8 出力 必要な出力は-になります Area parallelogram is : 48 アルゴリズム Step 1 - START Step 2 - Declare three

  2. PythonでDecimalを他のベースにすばやく変換する

    Pythonには、10進数を2進数、8進数、16進数などの他の基数に変換する簡単な方法がいくつかあります。たとえば、数値が10進数で19の場合、2進数では10011と表示され、8進数では23と表示され、16進数では13と表示されます。 結果として、2進数、8進数、16進数のそれぞれの前に、0b、0o、0xが表示されます。これらの表記を使用すると、数値の基数を簡単に判別できます。 サンプルコード #using bin(), oct(), hex() functions x = 242 print(The number {} in binary form: {}.format(x, b