-
Notifications
You must be signed in to change notification settings - Fork 0
/
int2bin.go
60 lines (52 loc) · 1.17 KB
/
int2bin.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
57
58
59
60
package int2bin
import (
"fmt"
)
// Bin returns a binary representations of n (int, int8/16/32/64, uint, uint8/16/32/64) as a string. Returns an error
// if n is of non-integer type.
func Bin(n interface{}) (string, error) {
switch v := n.(type) {
case int:
return toBin(uint64(v), 32<<(^uint(0)>>32&1)), nil
case int8:
return toBin(uint64(v), 8), nil
case int16:
return toBin(uint64(v), 16), nil
case int32:
return toBin(uint64(v), 32), nil
case int64:
return toBin(uint64(v), 64), nil
case uint:
return toBin(uint64(v), 32<<(^uint(0)>>32&1)), nil
case uint8:
return toBin(uint64(v), 8), nil
case uint16:
return toBin(uint64(v), 16), nil
case uint32:
return toBin(uint64(v), 32), nil
case uint64:
return toBin(v, 64), nil
}
return "", fmt.Errorf("unsupported type %T", n)
}
func toBin(n uint64, len uint) string {
var activeBit uint64
var cnt = 0
var binString [80]byte
i := 0
for activeBit = 1 << (len - 1); activeBit > 0; activeBit /= 2 {
if (n & activeBit) == activeBit {
binString[i] = '1'
} else {
binString[i] = '0'
}
cnt++
if cnt == 4 {
i++
binString[i] = ' '
cnt = 0
}
i++
}
return string(binString[0 : i-1])
}