rts-sim-module/consts/bit.go

38 lines
889 B
Go
Raw Normal View History

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 {
2024-01-29 17:35:46 +08:00
by |= (1 << i)
} else {
2024-01-29 17:35:46 +08:00
by &= ((1 << i) ^ byte(0xff))
}
bs[bi] = by
return bs
}