是否有像Python中的bumps.packbits()这样的函数在Go中可用(从表示该数字的int数组中生成数字)?
https://numpy.org/doc/stable/reference/generated/numpy.packbits.html
例如:
[1, 0] -> 0b10
[0, 1] -> 0b01
目的是以紧凑的方式存储大型布尔值数组:
。存储[]bool{true, false, ...}
为0b10
,然后对它们进行位操作
下面是Labiew
中的一个示例https://zone.ni.com/reference/en-XX/help/371361R-01/glang/boolean_array_to_number/
一种可能(蛮力)如下:
将数组中的每个bool值转换为整型,然后将整型转换为字符串itoa()
使用join()将字符串数组转换为字符串
将字符串转换为以2为基数的数字
但是我想知道是否有一种更有效的方法来进行这种转换。
我正在尝试转换:
{true, false, true} -> 0b101
等
下面的方法可以做到:
func B2i(b bool) int {
if b {
return 1
}
return 0
}
func Bools2BinInt(u []bool) int64 {
v := []int{}
// []bool to []int
for _, item := range u {
v = append(v, B2i(item))
}
// []int to []string
w := []string{}
for _, item := range v {
w = append(w, strconv.Itoa(item))
}
// []string -> string
x := strings.Join(w, "")
// string to Int
y, _ := strconv.ParseInt(x, 2, 32)
return y
}