日期:2014-05-20  浏览次数:20830 次

如何输出正负数的二进制数,要八位的.
我写这个输出来有的五位,有的32位,怎么整?
public   class   binary   {

      public   static   void   main(String   args[])
      {
      byte   p,q;
      int   r;
      p=47;
      q=-47;
        r=p|q;
        System.out.println(Integer.toBinaryString(p));
      System.out.println(Integer.toBinaryString(q));
      System.out.println(Integer.toBinaryString(r));
     
     
      }
       
}

------解决方案--------------------
public class Test {

public String refineNumber(int number){
StringBuffer str =null;
str = new StringBuffer(Integer.toBinaryString(number).toString());
if(str.length() < 8){
for(int i =0;i <8-str.length()+1;i++){
str = str.insert(0, "0 ");
}
}if(str.length() > 8){
str =new StringBuffer(str.substring(str.length()-8,str.length()));
}
else{
;
}
return str.toString();
}
public static void main(String args[]) {
byte p, q;
int r,x;
p = 47;
q = -47;
r = p | q;
x = 128;
Test t = new Test();
System.out.println(t.refineNumber(p));
System.out.println(Integer.toBinaryString(p));
System.out.println(Integer.toBinaryString(q));
System.out.println(t.refineNumber(q));
System.out.println(Integer.toBinaryString(r));
System.out.println(t.refineNumber(r));
System.out.println(t.refineNumber(x));
}

}