big numbers


Examples of creating big number types from and to uint, string, hex, and buffers.

Node.js

  1. const BN = require('bn.js')
  2. let bn = new BN(75)
  3. console.log(bn.toString(10))
  4. bn = new BN('75')
  5. console.log(bn.toString(10))
  6. bn = new BN(0x4b, 'hex')
  7. console.log(bn.toString(10))
  8. bn = new BN('4b', 'hex')
  9. console.log(bn.toString(10))
  10. bn = new BN(Buffer.from('4b', 'hex'))
  11. console.log(bn.toString(10))
  12. console.log(bn.toNumber(10))
  13. console.log(bn.toString('hex'))
  14. console.log(bn.toBuffer())
  15. let bn2 = new BN(5)
  16. let isEqual = bn.cmp(bn2) == 0
  17. console.log(isEqual)
  18. bn2 = new BN('4b', 'hex')
  19. isEqual = bn.cmp(bn2) == 0
  20. console.log(isEqual)

Output

  1. 75
  2. 75
  3. 75
  4. 75
  5. 75
  6. 75
  7. 4b
  8. <Buffer 4b>
  9. false
  10. true

Go

  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "math/big"
  6. )
  7. func main() {
  8. bn := new(big.Int)
  9. bn.SetUint64(75)
  10. fmt.Println(bn.String())
  11. bn = new(big.Int)
  12. bn.SetString("75", 10)
  13. fmt.Println(bn.String())
  14. bn = new(big.Int)
  15. bn.SetUint64(0x4b)
  16. fmt.Println(bn.String())
  17. bn = new(big.Int)
  18. bn.SetString("4b", 16)
  19. fmt.Println(bn.String())
  20. bn = new(big.Int)
  21. bn.SetBytes([]byte{0x4b})
  22. fmt.Println(bn.String())
  23. fmt.Println(bn.Uint64())
  24. fmt.Println(hex.EncodeToString(bn.Bytes()))
  25. fmt.Println(bn.Bytes())
  26. bn2 := big.NewInt(5)
  27. isEqual := bn.Cmp(bn2) == 0
  28. fmt.Println(isEqual)
  29. bn2 = big.NewInt(75)
  30. isEqual = bn.Cmp(bn2) == 0
  31. fmt.Println(isEqual)
  32. }

Output

  1. 75
  2. 75
  3. 75
  4. 75
  5. 75
  6. 75
  7. 4b
  8. [75]
  9. false
  10. true