Near constant time rotate that does not violate the standards

后端 未结 4 1391
孤街浪徒
孤街浪徒 2020-11-27 20:05

I\'m having a heck of a time trying to come up with a constant time rotate that does not violate the C/C++ standards.

The problem is the edge/corner cases, where ope

4条回答
  •  半阙折子戏
    2020-11-27 20:47

    Writing the expression as T((x<>(sizeof(T)*CHAR_BITS-y-1)>>1)) should yield defined behavior for all values of y below the bit size, assuming that T is an unsigned type with no padding. Unless the compiler has a good optimizer, the resulting code may not be as good as what would have been produced by your original expression. Having to put up with clunky hard to read code which will yield slower execution on many compilers is part of the price of progress, however, since a hyper-modern compiler which is given

    if (y) do_something();
    return T((x<>(sizeof(T)*8-y)));
    

    might improve the "efficiency" of the code by making the call to do_something unconditional.

    PS: I wonder if there are any real-world platforms where changing the definition of shift-right so that x >> y when y is precisely equal to the bit size of x, would be required to yield either 0 or x, but could make the choice in an arbitrary (unspecified) fashion, would require the platform to generate extra code or would preclude genuinely useful optimizations in non-contrived scenarios?

提交回复
热议问题