blob: 5e2ba0608784e8694b1455ee5842e28bc5c35b29 (
plain)
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
|
package util
import (
"fmt"
"strings"
)
func BitfieldString[T ~uint8 | ~uint16 | ~uint32 | ~uint64](bitfield T, bitnames []string) string {
var out strings.Builder
fmt.Fprintf(&out, "0x%0X", uint64(bitfield))
if bitfield == 0 {
out.WriteString("(none)")
} else {
rest := bitfield
sep := '('
for i := 0; rest != 0; i++ {
if rest&(1<<i) != 0 {
out.WriteRune(sep)
if i < len(bitnames) {
out.WriteString(bitnames[i])
} else {
fmt.Fprintf(&out, "(1<<%d)", i)
}
sep = '|'
}
rest &^= 1 << i
}
out.WriteRune(')')
}
return out.String()
}
|