简体   繁体   English

从文件读取位

[英]Read bits from file

How can i read bits from file ? 我如何从文件中读取位? I wrote bits to file something like that: 我写了一些类似的文件:

File plik=new File("bitowo");
  FileOutputStream fos=new FileOutputStream(plik);
  byte[] test =new byte[2];
  test[0]=(byte)01101000;
  test[1]=(byte)10101010;
  fos.write(test);
  fos.close();

and "bitowo" has only 2 bytes but how can i read from file "bitowo" bit after bit ? 和“ bitowo”只有2个字节,但是我怎么才能从文件“ bitowo”中逐位读取?

You can't read bit-by-bit. 您无法一点一点地阅读。 You can read byte-by-byte and then shift your byte bit-by-bit. 可以 逐字节读取 ,然后逐位移动字节

This: 这个:

test[0]=(byte)01101000;
test[1]=(byte)10101010;

Does not do what you think it does. 不执行您认为的操作。 Specifically, it does not write two bytes with the bit patterns that the code seems to suggest. 具体来说,它不会使用代码似乎建议的位模式写入两个字节。

The number 01101000 will be interpreted as an octal integer literal, because it starts with 0 . 数字01101000将被解释为八进制整数文字,因为它以0开头。 In decimal, that would be the number 295424 . 以十进制表示,即为295424 When you cast that to a byte , only the lower 8 bits are kept, and those happen to be 0 . 当您将其转换为byte ,仅保留低8位,而这些恰好是0 So the first byte in your file is 0 . 因此,文件中的第一个字节为0

The number 10101010 will be interpreted as a decimal integer literal (the number ten million, one hundred and one thousand and ten). 数字10101010将解释为十进制整数文字(数字一千万,一百一十一万零一)。 Again, by casting it to byte , only the lower 8 bits are kept, so the second byte in your file will contain the value 18 (decimal). 同样,通过将其强制转换为byte ,仅保留低8位,因此文件中的第二个字节将包含值18 (十进制)。

If you're using Java 7, you can use binary literals in your code by prefixing the digits with 0b : 如果您使用的是Java 7,则可以在代码中使用二进制文字,只需在数字前面加上0b

test[0]=(byte)0b01101000;
test[1]=(byte)0b10101010;

To read the two bytes back, just open the file with a FileInputStream and read two bytes from it. 要读回两个字节,只需使用FileInputStream打开文件并从中读取两个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM