38 lines
889 B
Go
38 lines
889 B
Go
package consts
|
|
|
|
import "fmt"
|
|
|
|
// 获取字节数组中的位值
|
|
// bs - 原始字节数组
|
|
// bitIndex - 位索引
|
|
func GetBitOfBytes(bs []byte, bitIndex int) bool {
|
|
bi := bitIndex / 8
|
|
i := bitIndex % 8
|
|
if bi >= len(bs) {
|
|
panic(fmt.Errorf("从字节数组获取位值错误,位索引超出字节数组范围: 数组len=%d,位索引=%d", len(bs), bitIndex))
|
|
}
|
|
by := bs[bi]
|
|
v := byte(1 << i)
|
|
return (by & v) == v
|
|
}
|
|
|
|
// 设置字节数组中的位值
|
|
// bs - 原始字节数组
|
|
// bitIndex - 位索引
|
|
// v - 位值
|
|
func SetBitOfBytes(bs []byte, bitIndex int, v bool) []byte {
|
|
bi := bitIndex / 8
|
|
i := bitIndex % 8
|
|
if bi >= len(bs) {
|
|
panic(fmt.Errorf("设置字节数组位值错误,位索引超出字节数组范围: 数组len=%d,位索引=%d", len(bs), bitIndex))
|
|
}
|
|
by := bs[bi]
|
|
if v {
|
|
by |= (1 << i)
|
|
} else {
|
|
by &= ((1 << i) ^ byte(0xff))
|
|
}
|
|
bs[bi] = by
|
|
return bs
|
|
}
|