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

前端 未结 16 1924
情深已故
情深已故 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:41

    Assuming you want to shift right by L bits, and the input x is a number with N bits:

    unsigned ror(unsigned x, int L, int N) 
    {
        unsigned lsbs = x & ((1 << L) - 1);
        return (x >> L) | (lsbs << (N-L));
    }
    

提交回复
热议问题