在JAVA中,通过InputStream得到数据,存入byte[]中,已知一个byte中有一个字节即8个位,我想获得每一个位

2025-01-05 02:45:13
推荐回答(3个)
回答1:

// byte转换成标准8位二进制的字符串
public static String byteToStandardBinay(byte b) {
String binaryStr = "0000000" + Integer.toBinaryString(b);
binaryStr = binaryStr.substring(binaryStr.length() - 8, binaryStr.length());
return binaryStr;
}
// main方法测试
public static void main(String[] args) throws Exception {
byte b = 44, b1 = 19, b2 = 58;
System.out.println(byteToStandardBinay(b));
// 将两个byte对应的二进制组合成16位的二进制
String combBinary = byteToStandardBinay(b1) + byteToStandardBinay(b2);
// 16位的二进制转换成10进制
int val = Integer.parseInt(combBinary, 2);
System.out.println(val);
}

回答2:

例子
InputStream is = null;
DataInputStream dis = null;
try {
is = new FileInputStream("c:/out.txt");
dis = new DataInputStream(is);
Short num = 0;
while(true){//每次2个字节地读取。就是读取一个short型
num = dis.readShort();
System.out.println(num);
}
} catch (Exception e) {
} finally{
try {
if(dis != null)
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}

回答3:

参考

java.lang.Object
extended by java.lang.Number
extended by java.lang.Integer

static String toBinaryString(int i)
Returns a string representation of the integer argument as an unsigned integer in base 2.