Add BitArray.Bytes()
This commit is contained in:
parent
9364accf1f
commit
1559ae1ac9
15
bit_array.go
15
bit_array.go
|
@ -1,6 +1,7 @@
|
|||
package common
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strings"
|
||||
|
@ -273,3 +274,17 @@ func (bA *BitArray) stringIndented(indent string) string {
|
|||
}
|
||||
return fmt.Sprintf("BA{%v:%v}", bA.Bits, strings.Join(lines, indent))
|
||||
}
|
||||
|
||||
func (bA *BitArray) Bytes() []byte {
|
||||
bA.mtx.Lock()
|
||||
defer bA.mtx.Unlock()
|
||||
|
||||
numBytes := (bA.Bits + 7) / 8
|
||||
bytes := make([]byte, numBytes)
|
||||
for i := 0; i < len(bA.Elems); i++ {
|
||||
elemBytes := [8]byte{}
|
||||
binary.LittleEndian.PutUint64(elemBytes[:], bA.Elems[i])
|
||||
copy(bytes[i*8:], elemBytes[:])
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package common
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
@ -118,3 +119,32 @@ func TestPickRandom(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBytes(t *testing.T) {
|
||||
bA := NewBitArray(4)
|
||||
bA.SetIndex(0, true)
|
||||
check := func(bA *BitArray, bz []byte) {
|
||||
if !bytes.Equal(bA.Bytes(), bz) {
|
||||
panic(Fmt("Expected %X but got %X", bz, bA.Bytes()))
|
||||
}
|
||||
}
|
||||
check(bA, []byte{0x01})
|
||||
bA.SetIndex(3, true)
|
||||
check(bA, []byte{0x09})
|
||||
|
||||
bA = NewBitArray(9)
|
||||
check(bA, []byte{0x00, 0x00})
|
||||
bA.SetIndex(7, true)
|
||||
check(bA, []byte{0x80, 0x00})
|
||||
bA.SetIndex(8, true)
|
||||
check(bA, []byte{0x80, 0x01})
|
||||
|
||||
bA = NewBitArray(16)
|
||||
check(bA, []byte{0x00, 0x00})
|
||||
bA.SetIndex(7, true)
|
||||
check(bA, []byte{0x80, 0x00})
|
||||
bA.SetIndex(8, true)
|
||||
check(bA, []byte{0x80, 0x01})
|
||||
bA.SetIndex(9, true)
|
||||
check(bA, []byte{0x80, 0x03})
|
||||
}
|
||||
|
|
2
int.go
2
int.go
|
@ -20,7 +20,7 @@ func SearchUint64s(a []uint64, x uint64) int {
|
|||
|
||||
func (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) }
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
//--------------------------------------------------------------------------------
|
||||
|
||||
func PutUint64LE(dest []byte, i uint64) {
|
||||
binary.LittleEndian.PutUint64(dest, i)
|
||||
|
|
Loading…
Reference in New Issue