-
Notifications
You must be signed in to change notification settings - Fork 0
/
intSquareOfTwo.go
98 lines (91 loc) · 1.68 KB
/
intSquareOfTwo.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"fmt"
"strconv"
"unsafe"
)
func SliceOfBytes(intValue int) bool {
if intValue < 0 {
intValue = -intValue
}
a := int64(intValue)
if a == 1 {
return false
}
byteSliceRev := *(*[8]byte)(unsafe.Pointer(&a))
byteSlice := make([]byte, 8)
firstByteFound := -1
for i := 0; i < 8; i++ {
byteSlice[i] = byteSliceRev[7-i]
if byteSlice[i] > 128 {
return false
}
if byteSlice[i] != 0 {
if firstByteFound != -1 {
return false
}
firstByteFound = i
}
}
if firstByteFound == -1 {
return false
}
binValue := fmt.Sprintf("%b", byteSlice[firstByteFound])
firstBitFound := false
for i := 0; i < len(binValue); i++ {
if binValue[i:i+1] == "1" {
if firstBitFound {
return false
}
firstBitFound = true
}
}
return firstBitFound
}
func StrConvToBytes(intValue int) bool {
if intValue < 0 {
intValue = -intValue
}
if intValue == 1 {
return false
}
binValue := strconv.FormatInt(int64(intValue), 2)
firstBitFound := false
for i := 0; i < len(binValue); i++ {
if binValue[i:i+1] == "1" {
if firstBitFound {
return false
}
firstBitFound = true
}
}
return firstBitFound
}
func BitShiftLeft(intValue int, shift int) (int, error){
newInt := intValue << shift
if newInt == 0 {
return 0, fmt.Errorf("overflow shifting of number %d", intValue)
}
return newInt, nil
}
func BitShift(intValue int) bool {
if intValue < 0 {
intValue *= -1
}
var base int = 2
var err error
for base <= intValue {
if intValue == base {
return true
}
base, err = BitShiftLeft(base, 1)
if err != nil {
fmt.Printf("Error while shifting: %v",err)
return false
}
}
return false
}
func main() {
fmt.Println(BitShift(256))
}