解析和格式化 Java 中的 BigInteger 到二進位制


首先,獲取兩個 BigInteger 物件並設定值。

BigInteger one, two;
one = new BigInteger("99");
two = new BigInteger("978");

現在,解析 BigInteger 物件“two”為二進位制。

two = new BigInteger("1111010010", 2);
String str = two.toString(2);

在上文,我們使用了以下建構函式。在此,對於 BigInteger 建構函式和 toString() 方法,基數都設定為表示二進位制的 2。

BigInteger(String val, int radix)

此建構函式用於將指定的基數中 BigInteger 的 String 表示轉換為 BigInteger。

以下是示例

示例

 線上演示

import java.math.*;
public class Demo {
   public static void main(String[] args) {
      BigInteger one, two;
      one = new BigInteger("99");
      // parsing BigInteger object "two" into Binary
      two = new BigInteger("1111010010", 2);
      String str = two.toString(2);
      System.out.println("Result (BigInteger) : " +one);
      System.out.println("Result after parsing : " +str);
   }
}

輸出

Result (BigInteger) : 99
Result after parsing : 1111010010

更新時間: 2020-6-29

1K+ 瀏覽量

開啟你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.