问题描述
要读/,我使用DataInputStream以/ DataOutputStream类写的二进制文件,他们有这种方法writeByte()/ readByte(),但我想要做的是读/写位是什么?是否可以?
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 possible?
我想使用它的COM pression算法,所以当我的COM pressing我想写3位(一个号码,并且仍有成千上万这样的数字在一个文件中),如果我在每次写一个字节我需要写3位,我会写的冗余数据的负载...
I want to use it for a compression algorithm, so when I am compressing I want to write 3 bits(for one number and there are millions of such numbers in a file) and if I write a byte at everytime I need to write 3 bits, I will write loads of redundant data...
推荐答案
这是不可能直接读/写各个位,最小的单位,你可以读/写是字节。
It's not possible to read/write individual bits directly, the smallest unit you can read/write is a byte.
您可以使用标准的运营商虽然操纵字节,所以如得到一个字节的最低2位,你会做
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;
低4位设置为1,并写入字节:
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)
这篇关于是否可以读/用JAVA写入文件的位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!