patterncModerate
Logical shift with signed numbers
Viewed 0 times
shiftwithnumberssignedlogical
Problem
I am going through the Coursera course The Hardware/Software Interface and because it has already ended, I would not be able to get any feedback on the code.
The assignment is:
LogicalShift: shift
I am wondering if shifting by
The assignment is:
LogicalShift: shift
x to the right by n, using a logical shift. We can assume that 0 ≤ n ≤ 31.I am wondering if shifting by
n and then back by 1 is a good solution. int logicalShift(int x, int n) {
int ba = 1>n; //shift the number
int msbShifted = (a >> n) << 1; //shift the MSB by n -1
//if negative ^ the leading 1's to create a logical shift
return msbShifted ^ numShifted;
}Solution
The C standard does not guarantee that an
The C standard says (C99 §6.5.7):
The result of
Therefore, your best bet is to treat
int is 32 bits. Even though the problem guarantees that 0 ≤ n ≤ 31, your code fails if run on a machine with a 64-bit int. One way to resolve that problem is to be explicit about the size of your inputs:#include
int32_t logicalShift(int32_t x, int n) {
…
}The C standard says (C99 §6.5.7):
The result of
E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of \$\dfrac{\mathrm{E1}}{2 ^ \mathrm{E2}}\$. If E1 has a signed type and a negative value, the resulting value is implementation-defined.Therefore, your best bet is to treat
x as an unsigned type:int logicalShift(int x, int n) {
return (unsigned int)x >> n;
}Code Snippets
#include <stdint.h>
int32_t logicalShift(int32_t x, int n) {
…
}int logicalShift(int x, int n) {
return (unsigned int)x >> n;
}Context
StackExchange Code Review Q#65037, answer score: 12
Revisions (0)
No revisions yet.