int logicalShift(int x, int n);
- User
int logicalShift(int x, int n);
- Assistant
The
logicalShiftfunction is typically used to perform a logical right shift on an integerxbynpositions. In logical shifting, zeros are shifted in from the left, regardless of the sign of the original number. This is different from arithmetic shifting, where the sign bit is replicated for signed integers.In C, the
>>operator performs an arithmetic shift for signed integers. To implement a logical shift using standard C constructs, especially for signed integers, you need to account for the sign bit after the shift.Here's a sample implementation of a
logicalShiftfunction in C:int logicalShift(int x, int n) { // Initialize mask to handle overflow from the left side during the shift int mask = (1 << 31) >> n << 1; // Create a mask with leading zeros for n-bits return (x >> n) & ~mask; // Apply mask to ensure leading bits are zeroed }