I was trying to make some code in C++ about “bitwise rotation” and I would like to make this by the left shif. I didn’t know how to code this, but I found a little code in “
Following code works great
#include
std::uint32_t rotl(std::uint32_t v, std::int32_t shift) {
std::int32_t s = shift>=0? shift%32 : -((-shift)%32);
return (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 the test for it.
#include
int main(){
using namespace std;
cout<
maybe I not provided the fastest implementation, but a portable and stable one for sure
Generic version
#include
template< class T>
inline T rotl( T v, std::int32_t shift){
std::size_t m = sizeof(v)*std::numeric_limits::digits;
T s = shift>=0? shift%m: -((-shift)%m)
return (v<>(m-s));
}
template< class T>
inline T rotr( T v, std::int32_t shift){
std::size_t m = sizeof(v)*std::numeric_limits::digits;
T s = shift>=0? shift%m: -((-shift)%m)
return (v>>s) | (v<<(m-s));
}
Cheers :)