From df7afcd9bec0f600b92f49f93a19fdce08afcfa0 Mon Sep 17 00:00:00 2001 From: q191201771 <191201771@qq.com> Date: Sun, 24 May 2020 00:07:52 +0800 Subject: [PATCH] =?UTF-8?q?[fix]=20package=20nazabits:=20BitWriter::WriteB?= =?UTF-8?q?it=E5=A6=82=E6=9E=9C=E5=8E=9F=E6=95=B0=E6=8D=AE=E4=B8=8D?= =?UTF-8?q?=E4=B8=BA=E9=9D=9E=E9=9B=B6=E5=80=BC=E6=97=B6=EF=BC=8C=E4=BC=9A?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E8=A6=86=E7=9B=96=E9=9D=9E=E5=86=99=E5=85=A5?= =?UTF-8?q?=E7=9A=84=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/nazabits/bits.go | 6 +++++- pkg/nazabits/bits_test.go | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/pkg/nazabits/bits.go b/pkg/nazabits/bits.go index 1015a03..47f43f6 100644 --- a/pkg/nazabits/bits.go +++ b/pkg/nazabits/bits.go @@ -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 diff --git a/pkg/nazabits/bits_test.go b/pkg/nazabits/bits_test.go index 737722d..a3b1c19 100644 --- a/pkg/nazabits/bits_test.go +++ b/pkg/nazabits/bits_test.go @@ -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) {