按位旋转(循环移位) [英] Bitwise rotation (Circular shift)

查看:197
本文介绍了按位旋转(循环移位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让一些C code ++关于按位轮换,我想由左人员健康保险基金,使这个。我不知道如何code,但我发现了一个小code在维基百科是这样的。

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 "Wikipedia" like this.

unsigned int rotl(unsigned int value, int shift) {
return (value << shift) | (value >> (sizeof(value) * CHAR_BIT - shift));
}

然后我试图使它工作,但这code不给我所期望的输出。防爆。我有一些无符号整型12 ,二进制1100,当我想通过上面的code的左人员健康保险基金做按位旋转,输出和无符号整型24 ,(11000),它不得不放弃输出无符号整型9 ,因为如果我做按位旋转(左SHIF),第一个MSB位现在已经是第一位,而所有其他位具有移动一个位离开了。

Then I tried to make it work, but this code don’t give the output that I expected. Ex. I have the number unsigned int 12, in binary 1100, and when I want to do bitwise rotation by the left shif with the code above, the output is and unsigned int 24,( 11000), and it had to give the output unsigned int 9, because if I make the bitwise rotation(left shif), the first MSB bit have to be now the first bit, and all the others bits have to move one bit to left.

您可以帮助理解是什么呢?这个问题,或者如果我做错了什么。

Can you help to understand what is the problem of that ?, or if I am doing something wrong.

感谢您。

推荐答案

继code的伟大工程

#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));
}

和当然的考验吧。

#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;
}

也许我不能提供最快的实现,但便携,稳定的一个肯定。

maybe I not provided the fastest implementation, but a portable and stable one for sure

通用版

#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>>(m-s));
}

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<<(m-s));
}

干杯:)

这篇关于按位旋转(循环移位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆