Bitwise rotation (Circular shift)

前端 未结 5 1797
粉色の甜心
粉色の甜心 2021-01-05 08:04

I was trying to make some code in C++ about “bitwise rotation” and I would like to make this by the left shif. I didn’t know how to code this, but I found a little code in “

5条回答
  •  心在旅途
    2021-01-05 08:35

    Following code works great

    #include 
    
    std::uint32_t rotl(std::uint32_t v, std::int32_t shift) {
        std::int32_t s =  shift>=0? shift%32 : -((-shift)%32);
        return (v<>(32-s));
    }
    
    std::uint32_t rotr(std::uint32_t v, std::int32_t shift) {
        std::int32_t s =  shift>=0? shift%32 : -((-shift)%32);
        return (v>>s) | (v<<(32-s));
    }
    

    and of course the test for it.

    #include 
    
    int main(){
       using namespace std;
       cout<

    maybe I not provided the fastest implementation, but a portable and stable one for sure

    Generic version

    #include 
    
    template< class T>
    inline T rotl( T v, std::int32_t shift){
        std::size_t m = sizeof(v)*std::numeric_limits::digits;
        T s = shift>=0? shift%m: -((-shift)%m)
        return (v<>(m-s));
    }
    
    template< class T>
    inline T rotr( T v, std::int32_t shift){
        std::size_t m = sizeof(v)*std::numeric_limits::digits;
        T s = shift>=0? shift%m: -((-shift)%m)
        return (v>>s) | (v<<(m-s));
    }
    

    Cheers :)

提交回复
热议问题