How can I perform arithmetic right shift in C in a portable way?

后端 未结 8 1724
挽巷
挽巷 2020-12-19 06:29

We are writing an emulator where we need sign propagating right shift. The emulated system uses 2\'s complement numbers.

I read that the >> operat

8条回答
  •  盖世英雄少女心
    2020-12-19 07:07

    Here is a simple hack that should work for all valid shift values:

    // shift x right y bits (0..31) with sign replication */
    uint32_t sar32(uint32_t x, uint32_t y) {
        uint32_t bottom = x >> y;
        uint32_t top = -((x & (1u << 31)) >> y);
        return top | bottom;
    }
    

    You might want to define the behavior for shift counts greater or equal to the word size:

    // shift x right y bits with sign replication, intel behavior */
    uint32_t sar32(uint32_t x, uint32_t y) {
        uint32_t bottom = x >> (y &= 31);
        uint32_t top = -((x & (1u << 31)) >> y);
        return top | bottom;
    }
    

提交回复
热议问题