Implementing Logical Right Shift in C

后端 未结 8 1157
心在旅途
心在旅途 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:31

    Milnex's answer is great and has an awesome explanation, but the implementation unfortunately fails due to the shift by total size. Here is a working version:

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

    To have 1 as the most significant bit, and all zeroes elsewhere, we need to shift 0x1 by number of bits - 1. I am submitting my own answer because my edit to the accepted answer was somehow rejected.

提交回复
热议问题