1
2
3
4
5
6
7
8
9
10 package sys
11
12
13
14 const deBruijn64ctz = 0x0218a392cd3d5dbf
15
16 var deBruijnIdx64ctz = [64]byte{
17 0, 1, 2, 7, 3, 13, 8, 19,
18 4, 25, 14, 28, 9, 34, 20, 40,
19 5, 17, 26, 38, 15, 46, 29, 48,
20 10, 31, 35, 54, 21, 50, 41, 57,
21 63, 6, 12, 18, 24, 27, 33, 39,
22 16, 37, 45, 47, 30, 53, 49, 56,
23 62, 11, 23, 32, 36, 44, 52, 55,
24 61, 22, 43, 51, 60, 42, 59, 58,
25 }
26
27 const deBruijn32ctz = 0x04653adf
28
29 var deBruijnIdx32ctz = [32]byte{
30 0, 1, 2, 6, 3, 11, 7, 16,
31 4, 14, 12, 21, 8, 23, 17, 26,
32 31, 5, 10, 15, 13, 20, 22, 25,
33 30, 9, 19, 24, 29, 18, 28, 27,
34 }
35
36
37
38 func Ctz64(x uint64) int {
39 x &= -x
40 y := x * deBruijn64ctz >> 58
41 i := int(deBruijnIdx64ctz[y])
42 z := int((x - 1) >> 57 & 64)
43 return i + z
44 }
45
46
47
48 func Ctz32(x uint32) int {
49 x &= -x
50 y := x * deBruijn32ctz >> 27
51 i := int(deBruijnIdx32ctz[y])
52 z := int((x - 1) >> 26 & 32)
53 return i + z
54 }
55
56
57 func Ctz8(x uint8) int {
58 return int(ntz8tab[x])
59 }
60
61
62
63 func Bswap64(x uint64) uint64 {
64 c8 := uint64(0x00ff00ff00ff00ff)
65 a := x >> 8 & c8
66 b := (x & c8) << 8
67 x = a | b
68 c16 := uint64(0x0000ffff0000ffff)
69 a = x >> 16 & c16
70 b = (x & c16) << 16
71 x = a | b
72 c32 := uint64(0x00000000ffffffff)
73 a = x >> 32 & c32
74 b = (x & c32) << 32
75 x = a | b
76 return x
77 }
78
79
80
81 func Bswap32(x uint32) uint32 {
82 c8 := uint32(0x00ff00ff)
83 a := x >> 8 & c8
84 b := (x & c8) << 8
85 x = a | b
86 c16 := uint32(0x0000ffff)
87 a = x >> 16 & c16
88 b = (x & c16) << 16
89 x = a | b
90 return x
91 }
92
View as plain text