Browse Source

Add BitArray.Bytes()

pull/1842/head
Jae Kwon 8 years ago
parent
commit
1559ae1ac9
3 changed files with 46 additions and 1 deletions
  1. +15
    -0
      bit_array.go
  2. +30
    -0
      bit_array_test.go
  3. +1
    -1
      int.go

+ 15
- 0
bit_array.go View File

@ -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
}

+ 30
- 0
bit_array_test.go View File

@ -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})
}

+ 1
- 1
int.go View File

@ -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…
Cancel
Save