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

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

    In details you can apply the following logic.

    If Bit Pattern is 33602 in Integer

    1000 0011 0100 0010
    

    and you need to Roll over with 2 right shifs then: first make a copy of bit pattern and then left shift it: Length - RightShift i.e. length is 16 right shift value is 2 16 - 2 = 14

    After 14 times left shifting you get.

    1000 0000 0000 0000
    

    Now right shift the value 33602, 2 times as required. You get

    0010 0000 1101 0000
    

    Now take an OR between 14 time left shifted value and 2 times right shifted value.

    1000 0000 0000 0000
    0010 0000 1101 0000
    ===================
    1010 0000 1101 0000
    ===================
    

    And you get your shifted rollover value. Remember bit wise operations are faster and this don't even required any loop.

提交回复
热议问题