Created
August 20, 2011 07:25
-
-
Save googya/1158800 to your computer and use it in GitHub Desktop.
将java的字节转换成二进制串,主要是利用了toBinaryString(int i) 这个函数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CountBytes { | |
public static void main(String[] args) throws IOException { | |
InputStream in; | |
if (args.length == 0){ | |
in = System.in; | |
}else | |
in = new FileInputStream(args[0]); | |
byte[] buff = new byte[10]; | |
int total = 0; | |
while (in.read(buff, 0, buff.length) != -1){ | |
total++; | |
} | |
System.out.println(total + " bytes"); | |
for (byte i : buff){ | |
String s = byte2bits(i); | |
System.out.print(s); | |
// System.out.println(i + ":"); | |
} | |
System.out.println(); | |
} | |
public static BitSet fromByte(byte b) | |
{ | |
BitSet bits = new BitSet(8); | |
for (int i = 0; i < 8; i++) | |
{ | |
bits.set(i, (b & 1) == 1); | |
b >>= 1; | |
} | |
return bits; | |
} | |
public static String byte2bits(byte b) { | |
int z = b; z |= 256; | |
String str = Integer.toBinaryString(z); | |
int len = str.length(); | |
return str.substring(len-8, len); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you.