Browse Source

Added a function countNumberOfBits()

tags/2021-05-28
jules 10 years ago
parent
commit
ed0bed9af7
2 changed files with 37 additions and 33 deletions
  1. +20
    -33
      modules/juce_core/maths/juce_BigInteger.cpp
  2. +17
    -0
      modules/juce_core/maths/juce_MathsFunctions.h

+ 20
- 33
modules/juce_core/maths/juce_BigInteger.cpp View File

@@ -311,37 +311,24 @@ void BigInteger::negate() noexcept
#pragma intrinsic (_BitScanReverse)
#endif
namespace BitFunctions
{
inline int countBitsInInt32 (uint32 n) noexcept
{
n -= ((n >> 1) & 0x55555555);
n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
n = (((n >> 4) + n) & 0x0f0f0f0f);
n += (n >> 8);
n += (n >> 16);
return (int) (n & 0x3f);
}
inline int highestBitInInt (uint32 n) noexcept
{
jassert (n != 0); // (the built-in functions may not work for n = 0)
#if JUCE_GCC
return 31 - __builtin_clz (n);
#elif JUCE_USE_INTRINSICS
unsigned long highest;
_BitScanReverse (&highest, n);
return (int) highest;
#else
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
return countBitsInInt32 (n >> 1);
#endif
}
inline static int highestBitInInt (uint32 n) noexcept
{
jassert (n != 0); // (the built-in functions may not work for n = 0)
#if JUCE_GCC
return 31 - __builtin_clz (n);
#elif JUCE_USE_INTRINSICS
unsigned long highest;
_BitScanReverse (&highest, n);
return (int) highest;
#else
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
return countBitsInInt32 (n >> 1);
#endif
}
int BigInteger::countNumberOfSetBits() const noexcept
@@ -349,7 +336,7 @@ int BigInteger::countNumberOfSetBits() const noexcept
int total = 0;
for (int i = (int) bitToIndex (highestBit) + 1; --i >= 0;)
total += BitFunctions::countBitsInInt32 (values[i]);
total += countNumberOfBits (values[i]);
return total;
}
@@ -361,7 +348,7 @@ int BigInteger::getHighestBit() const noexcept
const uint32 n = values[i];
if (n != 0)
return BitFunctions::highestBitInInt (n) + (i << 5);
return highestBitInInt (n) + (i << 5);
}
return -1;


+ 17
- 0
modules/juce_core/maths/juce_MathsFunctions.h View File

@@ -443,6 +443,23 @@ inline int nextPowerOfTwo (int n) noexcept
return n + 1;
}
/** Returns the number of bits in a 32-bit integer. */
inline int countNumberOfBits (uint32 n) noexcept
{
n -= ((n >> 1) & 0x55555555);
n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
n = (((n >> 4) + n) & 0x0f0f0f0f);
n += (n >> 8);
n += (n >> 16);
return (int) (n & 0x3f);
}
/** Returns the number of bits in a 64-bit integer. */
inline int countNumberOfBits (uint64 n) noexcept
{
return countNumberOfBits ((uint32) n) + countNumberOfBits ((uint32) (n >> 32));
}
/** Performs a modulo operation, but can cope with the dividend being negative.
The divisor must be greater than zero.
*/


Loading…
Cancel
Save