forked from zeta-chain/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbits.go
More file actions
56 lines (45 loc) · 1.57 KB
/
bits.go
File metadata and controls
56 lines (45 loc) · 1.57 KB
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
package math
import (
"math/bits"
)
// SetBit sets the bit at the given position (0-7) in the byte to 1
func SetBit(b *byte, position uint8) {
if position > 7 {
return
}
// Example: given b = 0b00000000 and position = 3
// step-1: shift value 1 to left by 3 times: 1 << 3 = 0b00001000
// step-2: make an OR operation with original byte to set the bit: 0b00000000 | 0b00001000 = 0b00001000
*b |= 1 << position
}
// IsBitSet returns true if the bit at the given position (0-7) is set in the byte, false otherwise
func IsBitSet(b byte, position uint8) bool {
if position > 7 {
return false
}
bitMask := byte(1 << position)
return b&bitMask != 0
}
// GetBits extracts the value of bits for a given mask
//
// Example: given b = 0b11011001 and mask = 0b11100000, the function returns 0b110
func GetBits(b byte, mask byte) byte {
extracted := b & mask
// get the number of trailing zero bits
trailingZeros := bits.TrailingZeros8(mask)
// remove trailing zeros
return extracted >> trailingZeros
}
// SetBits sets the value to the bits specified in the mask
//
// Example: given b = 0b00100001 and mask = 0b11100000, and value = 0b110, the function returns 0b11000001
func SetBits(b byte, mask byte, value byte) byte {
// get the number of trailing zero bits in the mask
trailingZeros := bits.TrailingZeros8(mask)
// shift the value left by the number of trailing zeros
valueShifted := value << trailingZeros
// clear the bits in 'b' that correspond to the mask
bCleared := b &^ mask
// Set the bits by ORing the cleared 'b' with the shifted value
return bCleared | valueShifted
}