juce_BigInteger.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. #ifndef JUCE_BIGINTEGER_H_INCLUDED
  22. #define JUCE_BIGINTEGER_H_INCLUDED
  23. //==============================================================================
  24. /**
  25. An arbitrarily large integer class.
  26. A BigInteger can be used in a similar way to a normal integer, but has no size
  27. limit (except for memory and performance constraints).
  28. Negative values are possible, but the value isn't stored as 2s-complement, so
  29. be careful if you use negative values and look at the values of individual bits.
  30. */
  31. class JUCE_API BigInteger
  32. {
  33. public:
  34. //==============================================================================
  35. /** Creates an empty BigInteger */
  36. BigInteger();
  37. /** Creates a BigInteger containing an integer value in its low bits.
  38. The low 32 bits of the number are initialised with this value.
  39. */
  40. BigInteger (uint32 value);
  41. /** Creates a BigInteger containing an integer value in its low bits.
  42. The low 32 bits of the number are initialised with the absolute value
  43. passed in, and its sign is set to reflect the sign of the number.
  44. */
  45. BigInteger (int32 value);
  46. /** Creates a BigInteger containing an integer value in its low bits.
  47. The low 64 bits of the number are initialised with the absolute value
  48. passed in, and its sign is set to reflect the sign of the number.
  49. */
  50. BigInteger (int64 value);
  51. /** Creates a copy of another BigInteger. */
  52. BigInteger (const BigInteger&);
  53. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  54. BigInteger (BigInteger&&) noexcept;
  55. BigInteger& operator= (BigInteger&&) noexcept;
  56. #endif
  57. /** Destructor. */
  58. ~BigInteger();
  59. //==============================================================================
  60. /** Copies another BigInteger onto this one. */
  61. BigInteger& operator= (const BigInteger&);
  62. /** Swaps the internal contents of this with another object. */
  63. void swapWith (BigInteger&) noexcept;
  64. //==============================================================================
  65. /** Returns the value of a specified bit in the number.
  66. If the index is out-of-range, the result will be false.
  67. */
  68. bool operator[] (int bit) const noexcept;
  69. /** Returns true if no bits are set. */
  70. bool isZero() const noexcept;
  71. /** Returns true if the value is 1. */
  72. bool isOne() const noexcept;
  73. /** Attempts to get the lowest 32 bits of the value as an integer.
  74. If the value is bigger than the integer limits, this will return only the lower bits.
  75. */
  76. int toInteger() const noexcept;
  77. /** Attempts to get the lowest 64 bits of the value as an integer.
  78. If the value is bigger than the integer limits, this will return only the lower bits.
  79. */
  80. int64 toInt64() const noexcept;
  81. //==============================================================================
  82. /** Resets the value to 0. */
  83. void clear();
  84. /** Clears a particular bit in the number. */
  85. void clearBit (int bitNumber) noexcept;
  86. /** Sets a specified bit to 1. */
  87. void setBit (int bitNumber);
  88. /** Sets or clears a specified bit. */
  89. void setBit (int bitNumber, bool shouldBeSet);
  90. /** Sets a range of bits to be either on or off.
  91. @param startBit the first bit to change
  92. @param numBits the number of bits to change
  93. @param shouldBeSet whether to turn these bits on or off
  94. */
  95. void setRange (int startBit, int numBits, bool shouldBeSet);
  96. /** Inserts a bit an a given position, shifting up any bits above it. */
  97. void insertBit (int bitNumber, bool shouldBeSet);
  98. /** Returns a range of bits as a new BigInteger.
  99. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  100. @see getBitRangeAsInt
  101. */
  102. BigInteger getBitRange (int startBit, int numBits) const;
  103. /** Returns a range of bits as an integer value.
  104. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  105. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  106. getBitRange().
  107. */
  108. uint32 getBitRangeAsInt (int startBit, int numBits) const noexcept;
  109. /** Sets a range of bits to an integer value.
  110. Copies the given integer onto a range of bits, starting at startBit,
  111. and using up to numBits of the available bits.
  112. */
  113. void setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
  114. /** Shifts a section of bits left or right.
  115. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  116. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  117. */
  118. void shiftBits (int howManyBitsLeft, int startBit);
  119. /** Returns the total number of set bits in the value. */
  120. int countNumberOfSetBits() const noexcept;
  121. /** Looks for the index of the next set bit after a given starting point.
  122. This searches from startIndex (inclusive) upwards for the first set bit,
  123. and returns its index. If no set bits are found, it returns -1.
  124. */
  125. int findNextSetBit (int startIndex) const noexcept;
  126. /** Looks for the index of the next clear bit after a given starting point.
  127. This searches from startIndex (inclusive) upwards for the first clear bit,
  128. and returns its index.
  129. */
  130. int findNextClearBit (int startIndex) const noexcept;
  131. /** Returns the index of the highest set bit in the number.
  132. If the value is zero, this will return -1.
  133. */
  134. int getHighestBit() const noexcept;
  135. //==============================================================================
  136. // All the standard arithmetic ops...
  137. BigInteger& operator+= (const BigInteger&);
  138. BigInteger& operator-= (const BigInteger&);
  139. BigInteger& operator*= (const BigInteger&);
  140. BigInteger& operator/= (const BigInteger&);
  141. BigInteger& operator|= (const BigInteger&);
  142. BigInteger& operator&= (const BigInteger&);
  143. BigInteger& operator^= (const BigInteger&);
  144. BigInteger& operator%= (const BigInteger&);
  145. BigInteger& operator<<= (int numBitsToShift);
  146. BigInteger& operator>>= (int numBitsToShift);
  147. BigInteger& operator++();
  148. BigInteger& operator--();
  149. BigInteger operator++ (int);
  150. BigInteger operator-- (int);
  151. BigInteger operator-() const;
  152. BigInteger operator+ (const BigInteger&) const;
  153. BigInteger operator- (const BigInteger&) const;
  154. BigInteger operator* (const BigInteger&) const;
  155. BigInteger operator/ (const BigInteger&) const;
  156. BigInteger operator| (const BigInteger&) const;
  157. BigInteger operator& (const BigInteger&) const;
  158. BigInteger operator^ (const BigInteger&) const;
  159. BigInteger operator% (const BigInteger&) const;
  160. BigInteger operator<< (int numBitsToShift) const;
  161. BigInteger operator>> (int numBitsToShift) const;
  162. bool operator== (const BigInteger&) const noexcept;
  163. bool operator!= (const BigInteger&) const noexcept;
  164. bool operator< (const BigInteger&) const noexcept;
  165. bool operator<= (const BigInteger&) const noexcept;
  166. bool operator> (const BigInteger&) const noexcept;
  167. bool operator>= (const BigInteger&) const noexcept;
  168. //==============================================================================
  169. /** Does a signed comparison of two BigIntegers.
  170. Return values are:
  171. - 0 if the numbers are the same
  172. - < 0 if this number is smaller than the other
  173. - > 0 if this number is bigger than the other
  174. */
  175. int compare (const BigInteger& other) const noexcept;
  176. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  177. Return values are:
  178. - 0 if the numbers are the same
  179. - < 0 if this number is smaller than the other
  180. - > 0 if this number is bigger than the other
  181. */
  182. int compareAbsolute (const BigInteger& other) const noexcept;
  183. /** Divides this value by another one and returns the remainder.
  184. This number is divided by other, leaving the quotient in this number,
  185. with the remainder being copied to the other BigInteger passed in.
  186. */
  187. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  188. /** Returns the largest value that will divide both this value and the one passed-in. */
  189. BigInteger findGreatestCommonDivisor (BigInteger other) const;
  190. /** Performs a combined exponent and modulo operation.
  191. This BigInteger's value becomes (this ^ exponent) % modulus.
  192. */
  193. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  194. /** Performs an inverse modulo on the value.
  195. i.e. the result is (this ^ -1) mod (modulus).
  196. */
  197. void inverseModulo (const BigInteger& modulus);
  198. //==============================================================================
  199. /** Returns true if the value is less than zero.
  200. @see setNegative, negate
  201. */
  202. bool isNegative() const noexcept;
  203. /** Changes the sign of the number to be positive or negative.
  204. @see isNegative, negate
  205. */
  206. void setNegative (bool shouldBeNegative) noexcept;
  207. /** Inverts the sign of the number.
  208. @see isNegative, setNegative
  209. */
  210. void negate() noexcept;
  211. //==============================================================================
  212. /** Converts the number to a string.
  213. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  214. If minimumNumCharacters is greater than 0, the returned string will be
  215. padded with leading zeros to reach at least that length.
  216. */
  217. String toString (int base, int minimumNumCharacters = 1) const;
  218. /** Reads the numeric value from a string.
  219. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  220. Any invalid characters will be ignored.
  221. */
  222. void parseString (StringRef text, int base);
  223. //==============================================================================
  224. /** Turns the number into a block of binary data.
  225. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  226. of the number, and so on.
  227. @see loadFromMemoryBlock
  228. */
  229. MemoryBlock toMemoryBlock() const;
  230. /** Converts a block of raw data into a number.
  231. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  232. of the number, and so on.
  233. @see toMemoryBlock
  234. */
  235. void loadFromMemoryBlock (const MemoryBlock& data);
  236. private:
  237. //==============================================================================
  238. HeapBlock<uint32> values;
  239. size_t numValues;
  240. int highestBit;
  241. bool negative;
  242. void ensureSize (size_t);
  243. void shiftLeft (int bits, int startBit);
  244. void shiftRight (int bits, int startBit);
  245. JUCE_LEAK_DETECTOR (BigInteger)
  246. };
  247. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  248. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  249. //==============================================================================
  250. #ifndef DOXYGEN
  251. // For backwards compatibility, BitArray is defined as an alias for BigInteger.
  252. typedef BigInteger BitArray;
  253. #endif
  254. #endif // JUCE_BIGINTEGER_H_INCLUDED