Best practices for circular shift (rotate) operations in C++

前端 未结 16 1601
情深已故
情深已故 2020-11-22 00:09

Left and right shift operators (<< and >>) are already available in C++. However, I couldn\'t find out how I could perform circular shift or rotate operations.

16条回答
  •  故里飘歌
    2020-11-22 00:44

    Since it's C++, use an inline function:

    template  
    INT rol(INT val) {
        return (val << 1) | (val >> (sizeof(INT)*CHAR_BIT-1));
    }
    

    C++11 variant:

    template  
    constexpr INT rol(INT val) {
        static_assert(std::is_unsigned::value,
                      "Rotate Left only makes sense for unsigned types");
        return (val << 1) | (val >> (sizeof(INT)*CHAR_BIT-1));
    }
    

提交回复
热议问题