我有一个按位编码值
0b00100110
,我想提取一个具有像[2,3,6]
这样的位位置的int数组。
我对 golang 非常陌生,所以来自 C 我会通过算法来完成此操作。但我希望它能走下去
No need to convert to strings. Look at standard "fmt" format.go how they are printing numbers in binary. The code below is a modification of that.
<pre><code>
type Ints interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uintptr
}
func NumberToBitsArray[T Ints](n T) []int32 {
const sz = 64
buf := [sz]int32{}
u := uint64(n)
i := sz
j := int32(0)
for u >= 1 {
i--
if u&1 > 0 {
buf[j] = int32(sz - i - 1)
j++
}
u >>= 1
}
return buf[0:j]
}
</pre>
</code>