Package bitmask ergänzt
parent
e8d7a62795
commit
db43edf5ce
@ -0,0 +1,41 @@
|
||||
package bitmask
|
||||
|
||||
import "unsafe"
|
||||
|
||||
// Sets the bit at pos in the integer n. pos = 0 is first.
|
||||
func SetBit(n int, pos uint) int {
|
||||
n |= (1 << pos)
|
||||
return n
|
||||
}
|
||||
|
||||
// Clears the bit at pos in n. pos = 0 is first.
|
||||
func ClearBit(n int, pos uint) int {
|
||||
mask := ^(1 << pos)
|
||||
n &= mask
|
||||
return n
|
||||
}
|
||||
|
||||
// Check if bit at pos n is set. pos = 0 is first.
|
||||
func HasBit(n int, pos uint) bool {
|
||||
val := n & (1 << pos)
|
||||
return (val > 0)
|
||||
}
|
||||
|
||||
// Sets the bit at pos in the integer n. pos = 0 is first.
|
||||
func Bit2Pos(n int) (pos uint) {
|
||||
poss := uint(unsafe.Sizeof(^int(0)) * 8) //Number of Bytes
|
||||
|
||||
for p := uint(0); p < poss; p++ {
|
||||
if n == 1<<p {
|
||||
return p
|
||||
}
|
||||
}
|
||||
|
||||
panic("Bit-position not found")
|
||||
}
|
||||
|
||||
// ... and reverse
|
||||
func Pos2Bit(pos uint) (n int) {
|
||||
n = 1 << pos
|
||||
return
|
||||
}
|
Loading…
Reference in New Issue