Circular-shift with variable bitlength For some memory masking operations I need a bitwise-rotation functionality for unsigned integral types. I came across solutions based on the wiki article, but have not found a variation for a function for bitwise-rotation within an "arbitrary" field of bits. Therefore, I have extended the solution of John Regehr, and now I want some feedback from you. I would also appreciate any advice on using mechanisms provided by the C++ core language up to C++14 (without the use of the std namespace).

#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;bitset&gt;

uint64_t CircShift (uint64_t x, uint8_t n, uint8_t bitwidth)
{
  return ((x&lt;&lt;n)&amp;((1&lt;&lt;bitwidth)-1)) | (x&gt;&gt;(bitwidth-n));
}

int main()
{
    uint64_t var=0b000110100110;
    var=CircShift(var,2,9);
    std::cout&lt;&lt;std::bitset&lt;12&gt;(var);

}
I think the function looks good. It does what it's supposed to do when the input is correct. However, if the input number x is larger or equal to 1&lt;&lt;bitwidth, the behavior is undefined. To rectify this, I suggest:

uint64_t CircShift(uint64_t x, uint8_t n, uint8_t bitwidth)
{
    return ((x&lt;&lt;n)&amp;((1&lt;&lt;bitwidth)-1)) | 
           ((x&amp;((1&lt;&lt;bitwidth)-1))&gt;&gt;(bitwidth-n));
}


Just add another mask to the right-shifted part. Also note that for shifts that are bigger than 64 bits, both your original function and my new function behave strangely. To rectify this, you can use the fact that a circular shift by bitlength steps simply give you the original number:

uint64_t CircShift(uint64_t x, uint8_t n, uint8_t bitwidth)
{
    return ((x&lt;&lt;(n%bitwidth))&amp;((1&lt;&lt;bitwidth)-1)) 
        | ((x&amp;((1&lt;&lt;bitwidth)-1))&gt;&gt;(bitwidth-(n%bitwidth)));
}