Implementing Logical Right Shift in C

后端 未结 8 1174
心在旅途
心在旅途 2020-11-29 07:07

I\'m working on making a logical right shift function in C using only bitwise operators. Here\'s what I have:

int logical_right_shift(int x, int n)
{
    int         


        
8条回答
  •  感情败类
    2020-11-29 07:24

    This is what you need:

    int logical_right_shift(int x, int n)
    {
        int size = sizeof(int) * 8; // usually sizeof(int) is 4 bytes (32 bits)
        return (x >> n) & ~(((0x1 << size) >> n) << 1);
    }
    

    Explain

    x >> n shifts n bits right. However, if x is negative, the sign bit (left-most bit) will be copied to its right, for example:

    Assume every int is 32 bits here, let
    x     = -2147483648 (10000000 00000000 00000000 00000000), then
    x >> 1 = -1073741824 (11000000 00000000 00000000 00000000)
    x >> 2 = -536870912  (11100000 00000000 00000000 00000000)
    and so on.

    So we need to erase out those sign extra sign bits when n is negative.

    Assume n = 5 here:

    0x1 << size moves 1 to the left-most position:

    (10000000 00000000 00000000 00000000)

    ((0x1 << size) >> n) << 1 copies 1 to its n-1 neighbors:

    (11111000 00000000 00000000 00000000)

    ~((0x1 << size) >> n) << 1! reverses all bits:

    (00000111 11111111 11111111 11111111)

    so we finally obtain a mask to extract what really need from x >> n:

    (x >> n) & ~(((0x1 << size) >> n) << 1)
    

    the & operation does the trick.

    And the total cost of this function is 6 operations.

提交回复
热议问题