Bitwise shift operation on a 128-bit number

后端 未结 5 708
礼貌的吻别
礼貌的吻别 2020-12-11 05:43

Lets say that I have an array of 4 32-bit integers which I use to store the 128-bit number

How can I perform left and right shift on this 128-bit number?

Tha

5条回答
  •  感动是毒
    2020-12-11 06:34

    Since you mentioned you're storing your 128-bit value in an array of 4 integers, you could do the following:

    void left_shift(unsigned int* array)
    {   
        for (int i=3; i >= 0; i--)
        {
            array[i] = array[i] << 1;
    
            if (i > 0)
            {
                unsigned int top_bit = (array[i-1] >> 31) & 0x1;
                array[i] = array[i] | top_bit;
            }
        }
    }
    
    void right_shift(unsigned int* array)
    {   
        for (int i=0; i < 4; i++)
        {
            array[i] = array[i] >> 1;
    
            if (i < 3)
            {
                unsigned int bottom_bit = (array[i+1] & 0x1) << 31;
                array[i] = array[i] | bottom_bit;
            }
        }
    }
    

提交回复
热议问题