github.com/jonasnick/go-ethereum@v0.7.12-0.20150216215225-22176f05d387/ethutil/big.go (about) 1 package ethutil 2 3 import "math/big" 4 5 // Big pow 6 // 7 // Returns the power of two big integers 8 func BigPow(a, b int) *big.Int { 9 c := new(big.Int) 10 c.Exp(big.NewInt(int64(a)), big.NewInt(int64(b)), big.NewInt(0)) 11 12 return c 13 } 14 15 // Big 16 // 17 // Shortcut for new(big.Int).SetString(..., 0) 18 func Big(num string) *big.Int { 19 n := new(big.Int) 20 n.SetString(num, 0) 21 22 return n 23 } 24 25 // BigD 26 // 27 // Shortcut for new(big.Int).SetBytes(...) 28 func BigD(data []byte) *big.Int { 29 n := new(big.Int) 30 n.SetBytes(data) 31 32 return n 33 } 34 35 func BitTest(num *big.Int, i int) bool { 36 return num.Bit(i) > 0 37 } 38 39 // To256 40 // 41 // "cast" the big int to a 256 big int (i.e., limit to) 42 var tt256 = new(big.Int).Lsh(big.NewInt(1), 256) 43 var tt256m1 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) 44 var tt255 = new(big.Int).Lsh(big.NewInt(1), 255) 45 46 func U256(x *big.Int) *big.Int { 47 //if x.Cmp(Big0) < 0 { 48 // return new(big.Int).Add(tt256, x) 49 // } 50 51 x.And(x, tt256m1) 52 53 return x 54 } 55 56 func S256(x *big.Int) *big.Int { 57 if x.Cmp(tt255) < 0 { 58 return x 59 } else { 60 // We don't want to modify x, ever 61 return new(big.Int).Sub(x, tt256) 62 } 63 } 64 65 func FirstBitSet(v *big.Int) int { 66 for i := 0; i < v.BitLen(); i++ { 67 if v.Bit(i) > 0 { 68 return i 69 } 70 } 71 72 return v.BitLen() 73 } 74 75 // Big to bytes 76 // 77 // Returns the bytes of a big integer with the size specified by **base** 78 // Attempts to pad the byte array with zeros. 79 func BigToBytes(num *big.Int, base int) []byte { 80 ret := make([]byte, base/8) 81 82 if len(num.Bytes()) > base/8 { 83 return num.Bytes() 84 } 85 86 return append(ret[:len(ret)-len(num.Bytes())], num.Bytes()...) 87 } 88 89 // Big copy 90 // 91 // Creates a copy of the given big integer 92 func BigCopy(src *big.Int) *big.Int { 93 return new(big.Int).Set(src) 94 } 95 96 // Big max 97 // 98 // Returns the maximum size big integer 99 func BigMax(x, y *big.Int) *big.Int { 100 if x.Cmp(y) <= 0 { 101 return y 102 } 103 104 return x 105 } 106 107 // Big min 108 // 109 // Returns the minimum size big integer 110 func BigMin(x, y *big.Int) *big.Int { 111 if x.Cmp(y) >= 0 { 112 return y 113 } 114 115 return x 116 }