Java lang.Long.toBinaryString() 方法帶示例


java.lang.Long.toBinaryString() 方法將 long 引數表示為 2 進位制的無符號整數形式的字串。

示例

以下示例演示如何實現 toBinaryString() 方法 −

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      long l = 190;
      System.out.println("Number = " + l);
      /* returns the string representation of the unsigned long value
      represented by the argument in binary (base 2) */
      System.out.println("Binary is " + Long.toBinaryString(l));
      // returns the number of one-bits
      System.out.println("Number of one bits = "
   }
}

輸出

Number = 190
Binary is 10111110
Number of one bits = 6

示例

下面我們再來看一個考慮負數的示例 −

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      long l = -25;
      System.out.println("Number = " + l);
      System.out.println("Binary is " + Long.toBinaryString(l));
      System.out.println("Number of one bits = " + Long.bitCount(l));
   }
}

輸出

Number = -25
Binary is 1111111111111111111111111111111111111111111111111111111111100111
Number of one bits = 62

更新於: 2019 年 9 月 24 日

99 瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.