Add BitArray.Bytes()

This commit is contained in:
Jae Kwon
2016-02-21 00:14:08 -08:00
parent 9364accf1f
commit 1559ae1ac9
3 changed files with 46 additions and 1 deletions

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
}