How to use MSVC intrinsics to get the equivalent of this GCC code?

后端 未结 5 1154
甜味超标
甜味超标 2020-11-29 06:46

The following code calls the builtin functions for clz/ctz in GCC and, on other systems, has C versions. Obviously, the C versions are a bit suboptimal if the system has a

5条回答
  •  时光说笑
    2020-11-29 07:32

    Bouncing from sh0dan code, the implementation should be corrected like this :

    #ifdef _MSC_VER
    #include 
    
    uint32_t __inline ctz( uint32_t value )
    {
        DWORD trailing_zero = 0;
    
        if ( _BitScanForward( &trailing_zero, value ) )
        {
            return trailing_zero;
        }
        else
        {
            // This is undefined, I better choose 32 than 0
            return 32;
        }
    }
    
    uint32_t __inline clz( uint32_t value )
    {
        DWORD leading_zero = 0;
    
        if ( _BitScanReverse( &leading_zero, value ) )
        {
           return 31 - leading_zero;
        }
        else
        {
             // Same remarks as above
             return 32;
        }
    }
    #endif
    

    As commented in the code, both ctz and clz are undefined if value is 0. In our abstraction, we fixed __builtin_clz(value) as (value?__builtin_clz(value):32) but it's a choice

提交回复
热议问题