What is the easiest way to check if a number is a power of 2 in C ++?
If you have a modern Intel processor with bit management instructions , you can do the following. It skips the direct C / C ++ code because others have already answered it, but you need it if the BMI is not available or not enabled.
bool IsPowerOf2_32(uint32_t x) { #if __BMI__ || ((_MSC_VER >= 1900) && defined(__AVX2__)) return !!((x > 0) && _blsr_u32(x)); #endif
GCC, ICC, and Clang signal BMI support with __BMI__ . It is available on Microsoft compilers in Visual Studio 2015 and later when AVX2 is available and enabled . See the header files for the built-in SIMD functions for the necessary headers .
I usually _blsr_u64 with _LP64_ in case of compilation on i686. Clang needs a little workaround because it uses a slightly different internal nam character:
#if defined(__GNUC__) && defined(__BMI__) # if defined(__clang__) # ifndef _tzcnt_u32 # define _tzcnt_u32(x) __tzcnt_u32(x) # endif # ifndef _blsr_u32 # define _blsr_u32(x) __blsr_u32(x) # endif # ifdef __x86_64__ # ifndef _tzcnt_u64 # define _tzcnt_u64(x) __tzcnt_u64(x) # endif # ifndef _blsr_u64 # define _blsr_u64(x) __blsr_u64(x) # endif # endif
Can you tell me a good website where you can find such an algorithm?
This site is often cited: Bit Twiddling Hacks .
jww Sep 20 '16 at 19:36 2016-09-20 19:36
source share