开发者

Bit Shifting in Place [closed]

Closed. This question needs debugging details. It is not currently accepting answers. 开发者_如何学Go

Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.

Closed 4 years ago.

Improve this question

I was just wondering if there was a way to bit shift a number "in place"? I've googled exactly that, and I can't find anything that pertains to what I want to do. Say I have the number 0b01001101, and I want to shift it twice to the right "in place", appending any numbers that fall off to the beginning. So it would look like 0b01010011. Is there any function in c++ that would allow me to bit shift left or right like that?


You want to implement a rotational shift

Here's a templatized version that should work with all types of ints (including shorts, chars, ints, and unsigned/signed alike).

template<class T>
T rotate_shift_right(T x, int shift)
{
    if ((shift > 0) && (shift < (sizeof(x)*8)))
    {
        x = ((unsigned)x >> shift) | (x << (sizeof(x) * 8 - shift));
    }
    return x;
}

template<class T>
T rotate_shift_left(T x, int shift)
{
    if ((shift > 0) && (shift < (sizeof(x)*8)))
    {
        x = (x << shift) | (((unsigned)x) >> (sizeof(x) * 8 - shift));
    }
    return x;
}


Write one yourself, I think it's not hard.

First store the right two bits,and then do the bit shift.Finally fill the left two bits with the stored bits.


Using the assembly instruction ror and getting the carry flag's value each time should do the work.

int rotate(int x, int n)
{
    for(int i = 0; i < n; i++) {
        __asm {
            ror   x, 1            ; rotate and store limit bit in cf
            lahf                  ; get part of flags in ah
            and   ah, 1           ; get only the cf
            shl   eax, 31         ; put it at the end
            and   x, eax          ; and store in x
        }
    }

    return x;
}


I think shifting it and then anding the last byte onto the beginning should work.


No, you should create your custom one


This is implemented as vendor-specific extensions. For MSVC, you can use _rotl8, _rotl16 (or _rotr* for rotating to the right). Not sure about GCC, but you can always drop to assembly and use the rol or ror.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜