问题

在Java中将int转换为二进制字符串表示形式的最佳方法(理想情况下,最简单)是什么?

例如,假设int是156.二进制字符串表示为"10011100"。


#1 热门回答(235 赞)

Integer.toBinaryString(int i)

#2 热门回答(30 赞)

还有java.lang.Integer.toString(int i, int base)方法,如果你的代码有一天可以处理2(二进制)以外的基数,那么这将更合适。


#3 热门回答(15 赞)

还有一种方法 - 使用java.lang.Integeryou可以获得第二个参数指定的第一个参数i的字符串表示形式。

Integer.toString(i, radix)

Example_

private void getStrtingRadix() {
        // TODO Auto-generated method stub
         /* returns the string representation of the 
          unsigned integer in concern radix*/
         System.out.println("Binary eqivalent of 100 = " + Integer.toString(100, 2));
         System.out.println("Octal eqivalent of 100 = " + Integer.toString(100, 8));
         System.out.println("Decimal eqivalent of 100 = " + Integer.toString(100, 10));
         System.out.println("Hexadecimal eqivalent of 100 = " + Integer.toString(100, 16));
    }

OutPut_

Binary eqivalent of 100 = 1100100
Octal eqivalent of 100 = 144
Decimal eqivalent of 100 = 100
Hexadecimal eqivalent of 100 = 64

原文链接