[fix] package nazabits: BitWriter::WriteBit如果原数据不为非零值时,会错误覆盖非写入的位

pull/2/head v0.12.2
q191201771 5 years ago
parent f31effc74c
commit df7afcd9be

@ -84,7 +84,11 @@ func NewBitWriter(b []byte) BitWriter {
// @param b: 当b不为0和1时取b的最低位
func (bw *BitWriter) WriteBit(b uint8) {
bw.core[bw.index] |= (b & 0x1) << (7 - bw.pos)
if b&0x1 == 1 {
bw.core[bw.index] |= 1 << (7 - bw.pos)
} else {
bw.core[bw.index] &= ^(1 << (7 - bw.pos))
}
bw.pos++
if bw.pos == 8 {
bw.pos = 0

@ -147,6 +147,19 @@ func TestBitWriter_WriteBit(t *testing.T) {
}
assert.Equal(t, uint8(48), v[0])
assert.Equal(t, uint8(57), v[1])
// 对非0原值进行位写入
v = []uint8{0xF0}
bw = nazabits.NewBitWriter(v)
bw.WriteBit(0)
bw.WriteBit(0)
bw.WriteBit(0)
bw.WriteBit(0)
bw.WriteBit(1)
bw.WriteBit(1)
bw.WriteBit(1)
bw.WriteBit(1)
assert.Equal(t, uint8(0x0F), v[0])
}
func TestBitWriter_WriteBits8(t *testing.T) {

Loading…
Cancel
Save