Skip to content

Commit

Permalink
Merge pull request #7377 from hzongaro/isPowerOf2-unsigned
Browse files Browse the repository at this point in the history
Define isPowerOf2 utility methods for unsigned
  • Loading branch information
0xdaryl committed Jul 5, 2024
2 parents 38148ea + 2b5fd40 commit 127e633
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions compiler/infra/Bit.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -394,12 +394,33 @@ static inline bool isNonPositivePowerOf2(int32_t input)
return (input & -input) == -input;
}

/**
* \brief Tests whether the operand is a power of 2
*
* \param input The 32-bit signed integer value to be tested
*
* \return \c true, if the operand is a power of 2;
* \c false, otherwise
*/
static inline bool isPowerOf2(int32_t input)
{
input = input < 0 ? -input : input;
return (input & -input) == input;
}

/**
* \brief Tests whether the operand is a power of 2
*
* \param input The 32-bit unsigned integer value to be tested
*
* \return \c true, if the operand is a power of 2;
* \c false, otherwise
*/
static inline bool isPowerOf2(uint32_t input)
{
return (input != 0) && (input & (input-1)) == 0;
}

static inline bool isNonNegativePowerOf2(int64_t input)
{
if (input == LONG_MIN)
Expand All @@ -417,12 +438,33 @@ static inline bool isNonPositivePowerOf2(int64_t input)
return (input & -input) == -input;
}

/**
* \brief Tests whether the operand is a power of 2
*
* \param input The 64-bit signed integer value to be tested
*
* \return \c true, if the operand is a power of 2;
* \c false, otherwise
*/
static inline bool isPowerOf2(int64_t input)
{
input = input < 0 ? -input : input;
return (input & -input) == input;
}

/**
* \brief Tests whether the operand is a power of 2
*
* \param input The 64-bit unsigned integer value to be tested
*
* \return \c true, if the operand is a power of 2;
* \c false, otherwise
*/
static inline bool isPowerOf2(uint64_t input)
{
return (input != 0) && (input & (input-1)) == 0;
}

#if defined(OSX)
// On OSX, intptr_t isn't int32_t nor int64_t

Expand Down

0 comments on commit 127e633

Please sign in to comment.