Java 程序将 int 转换为二进制字符串


Java 中的 Integer.toBinaryString() 方法将 int 转换为二进制字符串。

假设以下内容是我们的整数值。

int val1 = 9;
int val2 = 20;
int val3 = 2;

将上述 int 值转换为二进制字符串。

Integer.toBinaryString(val1);
Integer.toBinaryString(val2);
Integer.toBinaryString(val3);

示例

 实时演示

public class Demo {
   public static void main(String[] args) {
      int val1 = 9;
      int val2 = 20;
      int val3 = 30;
      int val4 = 78;
      int val5 = 2;
      System.out.println("Converting integer "+val1+" to Binary String: "+Integer.toBinaryString(val1));
      System.out.println("Converting integer "+val2+" to Binary String: "+Integer.toBinaryString(val2));
      System.out.println("Converting integer "+val3+" to Binary String: "+Integer.toBinaryString(val3));
      System.out.println("Converting integer "+val4+" to Binary String: "+Integer.toBinaryString(val4));
      System.out.println("Converting integer "+val5+" to Binary String: "+Integer.toBinaryString(val5));
   }
}

输出

Converting integer 9 to Binary String: 1001
Converting integer 20 to Binary String: 10100
Converting integer 30 to Binary String: 11110
Converting integer 78 to Binary String: 1001110
Converting integer 2 to Binary String: 10

更新于: 26-6-2020

5K+ 浏览

开启您的 职业 生涯

完成课程获得认证

开始
广告