Java - Integer toBinaryString() 方法



描述

Java Integer toBinaryString() 方法將整數引數作為無符號整數以 2 為底表示並返回其字串表示形式。

宣告

以下是 java.lang.Integer.toBinaryString() 方法的宣告

public static String toBinaryString(int i)

引數

i − 要轉換為字串的整數。

返回值

此方法返回引數表示的無符號整數值的二進位制(以 2 為底)字串表示形式。

異常

獲取正整數的二進位制表示示例

以下示例演示瞭如何使用 Integer toBinaryString() 方法獲取指定 int 值的二進位制字串表示形式。我們建立了一個 int 變數併為其分配了一個正 int 值。然後使用 toBinaryString() 方法列印結果。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      int i = 170;
      System.out.println("Number = " + i);
    
      /* returns the binary string representation of the given number */
      System.out.println("toBinaryString = " + Integer.toBinaryString(i));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Number = 170
toBinaryString = 10101010

獲取負整數的二進位制表示示例

以下示例演示瞭如何使用 Integer toBinaryString() 方法獲取指定 int 值的二進位制字串表示形式。我們建立了一個 int 變數併為其分配了一個負 int 值。然後使用 toBinaryString() 方法列印結果。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      int i = -170;
      System.out.println("Number = " + i);
    
      /* returns the binary string representation of the given number */
      System.out.println("toBinaryString = " + Integer.toBinaryString(i));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Number = -170
toBinaryString = 11111111111111111111111101010110

獲取正零整數的二進位制表示示例

以下示例演示瞭如何使用 Integer toBinaryString() 方法獲取指定 int 值的二進位制字串表示形式。我們建立了一個 int 變數併為其分配了一個零值。然後使用 toBinaryString() 方法列印結果。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      int i = 0;
      System.out.println("Number = " + i);
    
      /* returns the binary string representation of the given number */
      System.out.println("toBinaryString = " + Integer.toBinaryString(i));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Number = 0
toBinaryString = 0
java_lang_integer.htm
廣告

© . All rights reserved.