Skip to content

Commit b2f919e

Browse files
committed
Binary uint8 reversal
1 parent ef7ac78 commit b2f919e

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

binary_uint8_reversal/main.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
Binary integer order reversal. This is twist on the well-known string reversal. The idea is to swap
3+
the actual bits.
4+
5+
Go has a function that provides this functionality but this is home grown
6+
7+
*/
8+
9+
package main
10+
11+
import (
12+
"fmt"
13+
)
14+
15+
type test struct {
16+
original uint8
17+
expected uint8
18+
}
19+
20+
var tests []test
21+
22+
func main() {
23+
24+
for _, t := range tests {
25+
reversed := reverseUInt8(t)
26+
if reversed == t.expected {
27+
fmt.Printf("%d is the reverse of %d \n", t.expected, t.original)
28+
} else {
29+
panic("Not properly reversed")
30+
}
31+
}
32+
}
33+
34+
func reverseUInt8(t test) (rev uint8) {
35+
var oneUint8, bit uint8
36+
oneUint8 = byte(0b00000001)
37+
38+
rev = t.original
39+
for n := 7; n >= 4; n-- {
40+
lBit := (rev >> n) & oneUint8
41+
rBit := (rev >> (7 - n)) & oneUint8
42+
// Could actually be a constant
43+
bit = ^(oneUint8 << (7 - n)) //all ones but one bit
44+
rev = (rev & bit) | lBit<<(7-n)
45+
bit = ^(oneUint8 << n) //all ones but one bit
46+
rev = (rev & bit) | rBit<<n
47+
}
48+
return
49+
}
50+
51+
func init() {
52+
tests = append(tests, test{85, 170})
53+
tests = append(tests, test{0, 0})
54+
tests = append(tests, test{255, 255})
55+
tests = append(tests, test{240, 15})
56+
}

0 commit comments

Comments
 (0)