RT:
例如:            int a = 100;
            System.out.println (Integer.toBinaryString (a));            
        输出是:1100100        而我想的是输出8位的二进制数:01100100请教该如何实现

解决方案 »

  1.   

            DecimalFormat df=new DecimalFormat("00000000");
            System.out.println("ffffffffffffffffffff"+df.format(111111));
    result:ffffffffffffffffffff00111111
      

  2.   

    static String getBinaryFromInt(int b) {
    StringBuffer sb = new StringBuffer();
    for (int i = 7; i >= 0; i--) {
    sb.append(((b & (1 << i)) != 0) ? '1' : '0');
    }
    return sb.toString();
    }输出是:01100100
      

  3.   

    public static void main(String[] args) {
     int a = 100;
     String bin = Integer.toBinaryString(a);
             System.out.println (Integer.toBinaryString (a));
             DecimalFormat df = new DecimalFormat("00000000");
             String format = df.format(Integer.valueOf(bin));
             System.out.println(format);
    }
      

  4.   


    public class Test {
        public static void main(String[] args) {
            int a = 100;
            System.out.println(Integer.toBinaryString(a));
            System.out.println(convert(Integer.toBinaryString(a), 8));
        }    private static String convert(String str, int length) {
            if (str.length() < length) {
                String temp = "";
                for (int i = 0; i < length - str.length(); i++) {
                    temp += "0";
                }
                return temp + str;
            }
            return str;
        }
    }
      

  5.   

    +1不过为了扩大范围,可以把String format = df.format(Integer.valueOf(bin));
    改为String format = df.format(Long.valueOf(bin));
      

  6.   

    +1用 DecimalFormat 简直浪费!
      

  7.   

    DecimalFormat df = new DecimalFormat("00000000"); 就是指定它的输出格式,如果有数的会显示原来的数字,没有的显示0,你输入的是7位,因为最开始的0被省略了下面的Integer.valueOf(bin) 是因为通过format出来的是个String类型,但你查看API时df.format(...)中传的没有String这个类型,所以我只是把他转为Int类型而已