The following code works fine
#include <cstdint> std::uint32_t rotl(std::uint32_t v, std::int32_t shift) { std::int32_t s = shift>=0? shift%32 : -((-shift)%32); return (v<<s) | (v>>(32-s)); } std::uint32_t rotr(std::uint32_t v, std::int32_t shift) { std::int32_t s = shift>=0? shift%32 : -((-shift)%32); return (v>>s) | (v<<(32-s)); }
and of course a test for him.
#include <iostream> int main(){ using namespace std; cout<<rotr(8,1)<<endl; // 4 cout<<rotr(8,-1)<<endl; //16 cout<<rotl(8,1)<<endl; //16 cout<<rotl(8,-1)<<endl; //4 cout<<rotr(4,60)<<endl; //64 cout<<rotr(4,61)<<endl; //32 cout<<rotl(4,3)<<endl; //32 cout<<rotl(4,4)<<endl; //64 return 0; }
I may not have provided the fastest implementation, but portable and stable for sure
General version
#include <cstdint> template< class T> inline T rotl( T v, std::int32_t shift){ std::size_t m = sizeof(v)*std::numeric_limits<T>::digits; T s = shift>=0? shift%m: -((-shift)%m) return (v<<s) | (v>>(ms)); } template< class T> inline T rotr( T v, std::int32_t shift){ std::size_t m = sizeof(v)*std::numeric_limits<T>::digits; T s = shift>=0? shift%m: -((-shift)%m) return (v>>s) | (v<<(ms)); }
Greetings :)
source share