简体   繁体   中英

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 ?

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 . In decimal, that would be the number 295424 . When you cast that to a byte , only the lower 8 bits are kept, and those happen to be 0 . So the first byte in your file is 0 .

The number 10101010 will be interpreted as a decimal integer literal (the number ten million, one hundred and one thousand and ten). 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).

If you're using Java 7, you can use binary literals in your code by prefixing the digits with 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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