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

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

    The correct answer is following:

    #define BitsCount( val ) ( sizeof( val ) * CHAR_BIT )
    #define Shift( val, steps ) ( steps % BitsCount( val ) )
    #define ROL( val, steps ) ( ( val << Shift( val, steps ) ) | ( val >> ( BitsCount( val ) - Shift( val, steps ) ) ) )
    #define ROR( val, steps ) ( ( val >> Shift( val, steps ) ) | ( val << ( BitsCount( val ) - Shift( val, steps ) ) ) )
    

提交回复
热议问题