Logical shift with signed numbers 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 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&lt;&lt;31; // set MSB to 1 
    int a = x &amp; ba; // MSB will be 1 if negative or 0 if positive number

    int numShifted = x&gt;&gt;n; //shift the number
    int msbShifted = (a &gt;&gt; n) &lt;&lt; 1; //shift the MSB by n -1 

    //if negative ^ the leading 1's to create a logical shift
    return msbShifted ^ numShifted;
}
The C standard does not guarantee that an 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 &lt;stdint.h&gt;

int32_t logicalShift(int32_t x, int n) {
    …
}




The C standard says (C99 §6.5.7):


  The result of E1 &gt;&gt; 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 &gt;&gt; n;
}