一个真正天真的实现,我希望它能帮助你理解这个想法。还未经测试,可能包含断接一个错误等...
class BitArray {
// public fields for example code, in real code encapsulate
public int bits=0; // actual count of stored bits
public byte[] buf=new byte[1];
private void doubleBuf() {
byte [] tmp = new byte[buf.length * 2];
System.arraycopy(buf, 0, tmp, 0, buf.length);
buf = tmp;
}
private int arrayIndex(int bitNum) {
return bitNum/8;
}
private int bitNumInArray(int bitNum) {
return bitNum & 7; // change to change bit order in buf's bytes
}
// returns how many elements of buf are actually in use, for saving etc.
// note that last element usually contains unused bits.
public int getUsedArrayElements() {
return arrayIndex(this.bits-1) + 1;
}
// bitvalue is 0 for 0, non-0 for 1
public void setBit(byte bitValue, int bitNum) {
if (bitNum >= this.bits || bitNum < 0) throw new InvalidArgumentException();
if (bitValue == 0) this.buf[arrayIndex(bitNum)] &= ~((byte)1 << bitNumInArray(bitNum));
else this.buf[arrayIndex(bitNum)] |= (byte)1 << bitNumInArray(bitNum);
}
public void addBit(int bitValue) {
// this.bits is old bit count, which is same as index of new last bit
if (this.buf.length <= arrayIndex(this.bits)) doubleBuf();
++this.bits;
setBit(bitValue, this.bits-1);
}
int readBit(int bitNum) { // return 0 or 1
if (bitNum >= this.bits || bitNum < 0) throw new InvalidArgumentException();
byte value = buf[arrayIndex(bitNum)] & ((byte)1 << bitNumInArray(bitNum));
return (value == 0) ? 0 : 1;
}
void addBits(int bitCount, int bitValues) {
for (int num = bitCount - 1 ; num >= 0 ; --num) {
// change loop iteration order to change bit order of bitValues
addBit(bitValues & (1 << num));
}
}
为了有效的解决方案,它应该使用int或长阵列,而不是字节数组,并且包括用于多个比特添加更有效的方法(添加部分bitValues
一次完整的buf
数组元素,而不是像上面那样一点一点的)。
要保存这一点,您需要保存buf的正确字节数,由getUsedArrayElements()
计算。
这没有任何意义。 2^6 <101 <2^7,所以它至少需要7位。如果您想将数字101作为字符处理,请使用char数组。并且当您的程序收到一个非0和1组成的数字时就会崩溃,例如2,13,102等 – djechlin
数字'101'是位的集合。我想创建存储二进制字符串,并具有较小的大小(我使用霍夫曼编码),然后原始文件与文本(UTF-8)的文件。 – user1518451
这不是一组比特。这是一个整数。该整数的二进制表示是“1100101”。唯一有点意义的解释是'1100101'。使用正确的数据类型。 – djechlin