-
Notifications
You must be signed in to change notification settings - Fork 79
/
bigint.go
137 lines (109 loc) · 2.28 KB
/
bigint.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package emit
import (
"encoding/binary"
"math/big"
"math/bits"
)
// wordSizeBytes is a size of a big.Word (uint) in bytes.`
const wordSizeBytes = bits.UintSize / 8
// BytesToInt converts data in little-endian format to
// an integer.
func BytesToInt(data []byte) *big.Int {
n := new(big.Int)
size := len(data)
if size == 0 {
return big.NewInt(0)
}
isNeg := data[size-1]&0x80 != 0
size = getEffectiveSize(data, isNeg)
if size == 0 {
if isNeg {
return big.NewInt(-1)
}
return big.NewInt(0)
}
lw := size / wordSizeBytes
ws := make([]big.Word, lw+1)
for i := 0; i < lw; i++ {
base := i * wordSizeBytes
for j := base + 7; j >= base; j-- {
ws[i] <<= 8
ws[i] ^= big.Word(data[j])
}
}
for i := size - 1; i >= lw*wordSizeBytes; i-- {
ws[lw] <<= 8
ws[lw] ^= big.Word(data[i])
}
if isNeg {
for i := 0; i <= lw; i++ {
ws[i] = ^ws[i]
}
shift := byte(wordSizeBytes-size%wordSizeBytes) * 8
ws[lw] = ws[lw] & (^big.Word(0) >> shift)
n.SetBits(ws)
n.Neg(n)
return n.Sub(n, big.NewInt(1))
}
return n.SetBits(ws)
}
// getEffectiveSize returns minimal number of bytes required
// to represent a number (two's complement for negatives).
func getEffectiveSize(buf []byte, isNeg bool) int {
var b byte
if isNeg {
b = 0xFF
}
size := len(buf)
for ; size > 0; size-- {
if buf[size-1] != b {
break
}
}
return size
}
// IntToBytes converts integer to a slice in little-endian format.
func IntToBytes(n *big.Int) []byte {
sign := n.Sign()
if sign == 0 {
return []byte{0}
}
var ws []big.Word
if sign == 1 {
ws = n.Bits()
} else {
n1 := new(big.Int).Add(n, big.NewInt(1))
if n1.Sign() == 0 { // n == -1
return []byte{0xFF}
}
ws = n1.Bits()
}
data := wordsToBytes(ws)
size := len(data)
for ; data[size-1] == 0; size-- {
}
data = data[:size]
if data[size-1]&0x80 != 0 {
data = append(data, 0)
}
if sign == -1 {
for i := range data {
data[i] = ^data[i]
}
}
return data
}
func wordsToBytes(ws []big.Word) []byte {
lb := len(ws) * wordSizeBytes
bs := make([]byte, lb, lb+1)
if wordSizeBytes == 8 {
for i := range ws {
binary.LittleEndian.PutUint64(bs[i*wordSizeBytes:], uint64(ws[i]))
}
} else {
for i := range ws {
binary.LittleEndian.PutUint32(bs[i*wordSizeBytes:], uint32(ws[i]))
}
}
return bs
}