Skip to content

Commit

Permalink
fix 2.63 2.66
Browse files Browse the repository at this point in the history
2.63 remove the use of if and <
2.66 fix case 0x80000000
  • Loading branch information
boltma committed Jun 8, 2018
1 parent 4bddfa2 commit ebf3ba1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
6 changes: 4 additions & 2 deletions chapter2/code/leftmost-one.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,17 @@ int leftmost_one(unsigned x) {
x |= x >> 8;
x |= x >> 16;
/*
* then, do mask & (~mask >> 1), reserve leftmost bit one
* then, do (mask >> 1) + (mask && 1), in which mask && 1 deals with case x = 0, reserve leftmost bit one
* that's we want
*/
return x & (~x >> 1);
return (x >> 1) + (x && 1);
}

int main(int argc, char* argv[]) {
assert(leftmost_one(0xFF00) == 0x8000);
assert(leftmost_one(0x6000) == 0x4000);
assert(leftmost_one(0x0) == 0x0);
assert(leftmost_one(0x80000000) == 0x80000000);
return 0;
}

Expand Down
14 changes: 10 additions & 4 deletions chapter2/code/srl-sra.c
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ int sra(int x, int k) {

int w = sizeof(int) << 3;
int mask = (int) -1 << (w - k);
if (x < 0) {
return xsrl | mask;
}
return xsrl;
//let mask remain unchanged when the first bit of x is 1, otherwise 0.
int m = 1 << (w - 1);
mask &= ! (x & m) - 1;
return xsrl | mask;
}

int main(int argc, char* argv[]) {
Expand All @@ -31,5 +31,11 @@ int main(int argc, char* argv[]) {
assert(srl(test_unsigned, 4) == test_unsigned >> 4);
assert(sra(test_int, 4) == test_int >> 4);

test_unsigned = 0x87654321;
test_int = 0x87654321;

assert (srl (test_unsigned, 4) == test_unsigned >> 4);
assert (sra (test_int, 4) == test_int >> 4);

return 0;
}

0 comments on commit ebf3ba1

Please sign in to comment.