Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

README.md 7.3 KiB

há 3 anos
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # <img src="./logo.png" alt="bn.js" width="160" height="160" />
  2. > BigNum in pure javascript
  3. [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js)
  4. ## Install
  5. `npm install --save bn.js`
  6. ## Usage
  7. ```js
  8. const BN = require('bn.js');
  9. var a = new BN('dead', 16);
  10. var b = new BN('101010', 2);
  11. var res = a.add(b);
  12. console.log(res.toString(10)); // 57047
  13. ```
  14. **Note**: decimals are not supported in this library.
  15. ## Notation
  16. ### Prefixes
  17. There are several prefixes to instructions that affect the way the work. Here
  18. is the list of them in the order of appearance in the function name:
  19. * `i` - perform operation in-place, storing the result in the host object (on
  20. which the method was invoked). Might be used to avoid number allocation costs
  21. * `u` - unsigned, ignore the sign of operands when performing operation, or
  22. always return positive value. Second case applies to reduction operations
  23. like `mod()`. In such cases if the result will be negative - modulo will be
  24. added to the result to make it positive
  25. ### Postfixes
  26. * `n` - the argument of the function must be a plain JavaScript
  27. Number. Decimals are not supported.
  28. * `rn` - both argument and return value of the function are plain JavaScript
  29. Numbers. Decimals are not supported.
  30. ### Examples
  31. * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a`
  32. * `a.umod(b)` - reduce `a` modulo `b`, returning positive value
  33. * `a.iushln(13)` - shift bits of `a` left by 13
  34. ## Instructions
  35. Prefixes/postfixes are put in parens at the of the line. `endian` - could be
  36. either `le` (little-endian) or `be` (big-endian).
  37. ### Utilities
  38. * `a.clone()` - clone number
  39. * `a.toString(base, length)` - convert to base-string and pad with zeroes
  40. * `a.toNumber()` - convert to Javascript Number (limited to 53 bits)
  41. * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`)
  42. * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero
  43. pad to length, throwing if already exceeding
  44. * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`,
  45. which must behave like an `Array`
  46. * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For
  47. compatibility with browserify and similar tools, use this instead:
  48. `a.toArrayLike(Buffer, endian, length)`
  49. * `a.bitLength()` - get number of bits occupied
  50. * `a.zeroBits()` - return number of less-significant consequent zero bits
  51. (example: `1010000` has 4 zero bits)
  52. * `a.byteLength()` - return number of bytes occupied
  53. * `a.isNeg()` - true if the number is negative
  54. * `a.isEven()` - no comments
  55. * `a.isOdd()` - no comments
  56. * `a.isZero()` - no comments
  57. * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b)
  58. depending on the comparison result (`ucmp`, `cmpn`)
  59. * `a.lt(b)` - `a` less than `b` (`n`)
  60. * `a.lte(b)` - `a` less than or equals `b` (`n`)
  61. * `a.gt(b)` - `a` greater than `b` (`n`)
  62. * `a.gte(b)` - `a` greater than or equals `b` (`n`)
  63. * `a.eq(b)` - `a` equals `b` (`n`)
  64. * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width
  65. * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width
  66. * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance
  67. * `BN.max(a, b)` - return `a` if `a` bigger than `b`
  68. * `BN.min(a, b)` - return `a` if `a` less than `b`
  69. ### Arithmetics
  70. * `a.neg()` - negate sign (`i`)
  71. * `a.abs()` - absolute value (`i`)
  72. * `a.add(b)` - addition (`i`, `n`, `in`)
  73. * `a.sub(b)` - subtraction (`i`, `n`, `in`)
  74. * `a.mul(b)` - multiply (`i`, `n`, `in`)
  75. * `a.sqr()` - square (`i`)
  76. * `a.pow(b)` - raise `a` to the power of `b`
  77. * `a.div(b)` - divide (`divn`, `idivn`)
  78. * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`)
  79. * `a.divRound(b)` - rounded division
  80. ### Bit operations
  81. * `a.or(b)` - or (`i`, `u`, `iu`)
  82. * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced
  83. with `andn` in future)
  84. * `a.xor(b)` - xor (`i`, `u`, `iu`)
  85. * `a.setn(b)` - set specified bit to `1`
  86. * `a.shln(b)` - shift left (`i`, `u`, `iu`)
  87. * `a.shrn(b)` - shift right (`i`, `u`, `iu`)
  88. * `a.testn(b)` - test if specified bit is set
  89. * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`)
  90. * `a.bincn(b)` - add `1 << b` to the number
  91. * `a.notn(w)` - not (for the width specified by `w`) (`i`)
  92. ### Reduction
  93. * `a.gcd(b)` - GCD
  94. * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`)
  95. * `a.invm(b)` - inverse `a` modulo `b`
  96. ## Fast reduction
  97. When doing lots of reductions using the same modulo, it might be beneficial to
  98. use some tricks: like [Montgomery multiplication][0], or using special algorithm
  99. for [Mersenne Prime][1].
  100. ### Reduction context
  101. To enable this tricks one should create a reduction context:
  102. ```js
  103. var red = BN.red(num);
  104. ```
  105. where `num` is just a BN instance.
  106. Or:
  107. ```js
  108. var red = BN.red(primeName);
  109. ```
  110. Where `primeName` is either of these [Mersenne Primes][1]:
  111. * `'k256'`
  112. * `'p224'`
  113. * `'p192'`
  114. * `'p25519'`
  115. Or:
  116. ```js
  117. var red = BN.mont(num);
  118. ```
  119. To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than
  120. `.red(num)`, but slower than `BN.red(primeName)`.
  121. ### Converting numbers
  122. Before performing anything in reduction context - numbers should be converted
  123. to it. Usually, this means that one should:
  124. * Convert inputs to reducted ones
  125. * Operate on them in reduction context
  126. * Convert outputs back from the reduction context
  127. Here is how one may convert numbers to `red`:
  128. ```js
  129. var redA = a.toRed(red);
  130. ```
  131. Where `red` is a reduction context created using instructions above
  132. Here is how to convert them back:
  133. ```js
  134. var a = redA.fromRed();
  135. ```
  136. ### Red instructions
  137. Most of the instructions from the very start of this readme have their
  138. counterparts in red context:
  139. * `a.redAdd(b)`, `a.redIAdd(b)`
  140. * `a.redSub(b)`, `a.redISub(b)`
  141. * `a.redShl(num)`
  142. * `a.redMul(b)`, `a.redIMul(b)`
  143. * `a.redSqr()`, `a.redISqr()`
  144. * `a.redSqrt()` - square root modulo reduction context's prime
  145. * `a.redInvm()` - modular inverse of the number
  146. * `a.redNeg()`
  147. * `a.redPow(b)` - modular exponentiation
  148. ### Number Size
  149. Optimized for elliptic curves that work with 256-bit numbers.
  150. There is no limitation on the size of the numbers.
  151. ## LICENSE
  152. This software is licensed under the MIT License.
  153. Copyright Fedor Indutny, 2015.
  154. Permission is hereby granted, free of charge, to any person obtaining a
  155. copy of this software and associated documentation files (the
  156. "Software"), to deal in the Software without restriction, including
  157. without limitation the rights to use, copy, modify, merge, publish,
  158. distribute, sublicense, and/or sell copies of the Software, and to permit
  159. persons to whom the Software is furnished to do so, subject to the
  160. following conditions:
  161. The above copyright notice and this permission notice shall be included
  162. in all copies or substantial portions of the Software.
  163. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  164. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  165. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  166. NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  167. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  168. OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  169. USE OR OTHER DEALINGS IN THE SOFTWARE.
  170. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication
  171. [1]: https://en.wikipedia.org/wiki/Mersenne_prime