forked from loxilb-io/loxilib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitop.go
89 lines (66 loc) · 1.46 KB
/
bitop.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// SPDX-License-Identifier: Apache 2.0
// Copyright (c) 2022 NetLOX Inc
package loxilib
import (
"math/bits"
)
// CountAllSetBitsInArr - count set bits in an array of uint8
func CountAllSetBitsInArr(arr []uint8) int {
var bCount int = 0
sz := len(arr)
for i := 0; i < sz; i++ {
bCount += bits.OnesCount8(arr[i])
}
return bCount
}
// CountSetBitsInArr - count set bits in an array of uint8 from bPos
func CountSetBitsInArr(arr []uint8, bPos int) int {
bCount := 0
if int(bPos) >= 8*len(arr) {
return -1
}
arrIdx := bPos / 8
bPosIdx := 7 - (bPos % 8)
for i := 0; i <= int(arrIdx); i++ {
var val uint8
if i == int(arrIdx) {
val = arr[i] >> bPosIdx & 0xff
} else {
val = arr[i]
}
bCount += bits.OnesCount8(val)
}
return bCount
}
// IsBitSetInArr - check given bPos bit is set in the array
func IsBitSetInArr(arr []uint8, bPos int) bool {
if int(bPos) >= 8*len(arr) {
return false
}
arrIdx := bPos / 8
bPosIdx := 7 - (bPos % 8)
if (arr[arrIdx]>>bPosIdx)&0x1 == 0x1 {
return true
}
return false
}
// SetBitInArr - set bPos bit in the array
func SetBitInArr(arr []uint8, bPos int) {
if int(bPos) >= 8*len(arr) {
return
}
arrIdx := bPos / 8
bPosIdx := 7 - (bPos % 8)
arr[arrIdx] |= 0x1 << bPosIdx
return
}
// UnSetBitInArr - unset bPos bit in the array
func UnSetBitInArr(arr []uint8, bPos int) {
if int(bPos) >= 8*len(arr) {
return
}
arrIdx := bPos / 8
bPosIdx := 7 - (bPos % 8)
arr[arrIdx] &= ^(0x1 << bPosIdx)
return
}