何よりも、これは私の宿題ではなく、Computer Systems A Programmer's Perspective (優れた本)という本によって与えられたラボです。
以下を使用せずに、符号付き整数に対して右に論理シフトを実行する必要があります。
- 鋳造
if,while,switch,for,do-while,?:- 任意の型のポインタ
許可されている演算子は次のとおりです。
! + ~ | >> << ^
これまでに何を試しましたか?
/*
* logicalShift - shift x to the right by n, using a logical shift
* Can assume that 0 <= n <= 31
* Examples: logicalShift(0x87654321,4) = 0x08765432
* Legal ops: ~ & ^ | + << >>
* Max ops: 20
* Rating: 3
*/
int logicalShift(int x, int n) {
int mask = ~0;
int shiftAmount = 31 + ((~n)+1);//this evaluates to 31 - n on two's complement machines
mask = mask << shiftAmount;
mask = ~mask;//If n equals 0, it means we have negated all bits and hence have mask = 0
x = x >> n;
return x & mask;
}
マスクがすべて 0 になり、関数が を返すため、このコードはn壊れます。00
完全なコードではなく、正しい方向へのヒントをいただければ幸いです。
繰り返しますが、これは宿題ではありません。ラボの割り当ては、 http://csapp.cs.cmu.edu/public/labs.htmlで公開されています。
PS: 重複ではありません。署名なしにキャストしてからシフトするソリューションを投稿しないでください。