big.go 2.0 KB

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