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
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;
}