-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
56 lines (45 loc) · 1.09 KB
/
main.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
/*
Binary integer order reversal. This is twist on the well-known string reversal. The idea is to swap
the actual bits.
Go has a function that provides this functionality but this is home grown
*/
package main
import (
"fmt"
)
type test struct {
original uint8
expected uint8
}
var tests []test
func main() {
for _, t := range tests {
reversed := reverseUInt8(t)
if reversed == t.expected {
fmt.Printf("%d is the reverse of %d \n", t.expected, t.original)
} else {
panic("Not properly reversed")
}
}
}
func reverseUInt8(t test) (rev uint8) {
var oneUint8, bit uint8
oneUint8 = byte(0b00000001)
rev = t.original
for n := 7; n >= 4; n-- {
lBit := (rev >> n) & oneUint8
rBit := (rev >> (7 - n)) & oneUint8
// Could actually be a constant
bit = ^(oneUint8 << (7 - n)) //all ones but one bit
rev = (rev & bit) | lBit<<(7-n)
bit = ^(oneUint8 << n) //all ones but one bit
rev = (rev & bit) | rBit<<n
}
return
}
func init() {
tests = append(tests, test{85, 170})
tests = append(tests, test{0, 0})
tests = append(tests, test{255, 255})
tests = append(tests, test{240, 15})
}