Is it possible to read/write bits from a file using JAVA?

后端 未结 9 930
一生所求
一生所求 2020-12-09 21:34

To read/write binary files, I am using DataInputStream/DataOutputStream, they have this method writeByte()/readByte(), but what I want to do is read/write bits? Is it possib

9条回答
  •  暖寄归人
    2020-12-09 22:24

    It's not possible to read/write individual bits directly, the smallest unit you can read/write is a byte.

    You can use the standard bitwise operators to manipulate a byte though, so e.g. to get the lowest 2 bits of a byte, you'd do

    byte b = in.readByte();
    byte lowBits = b&0x3;
    

    set the low 4 bits to 1, and write the byte:

    b |= 0xf;
    out.writeByte(b);
    

    (Note, for the sake of efficiency you might want to read/write byte arrays and not single bytes)

提交回复
热议问题