import java.io.*;public class Test4{ public static void main( String[] args ) throws Exception{ int hexInt = -128; System.out.println( Integer.toBinaryString( hexInt<0?hexInt+256:hexInt ) ); } }
??????????
在处理byte的二进制时,我一般都不用Integer.toBinaryString,我一般都会自己写一个helper方法,举例如下: static String getBinaryFromByte(byte b) { StringBuffer sb = new StringBuffer(); for (int i = 7; i >=0; i--) { sb.append(((b&(1<<i))!=0)?'1':'0'); } return sb.toString(); }
import java.io.*;public class Test4{ public static void main( String[] args ) throws Exception{ byte b = -127; int i = b<0?b+256:b; System.out.println( Integer.toBinaryString( i ) ); } }
我是从文件中把“80”作为一个byte取出来,它的值实际上-128
这时候,如何能得到字符串10000000
public static void main( String[] args ) throws Exception{
int hexInt = -128;
System.out.println( Integer.toBinaryString( hexInt<0?hexInt+256:hexInt ) );
}
}
??????????
StringBuffer sb = new StringBuffer();
for (int i = 7; i >=0; i--) {
sb.append(((b&(1<<i))!=0)?'1':'0');
}
return sb.toString();
}
public static void main( String[] args ) throws Exception{
byte b = -127;
int i = b<0?b+256:b;
System.out.println( Integer.toBinaryString( i ) );
}
}
这样更像你的要求一点