Skip to content

Commit

Permalink
fix solution 2.70
Browse files Browse the repository at this point in the history
  • Loading branch information
DreamAndDead committed May 28, 2018
1 parent b0fbef9 commit 4bddfa2
Showing 1 changed file with 21 additions and 13 deletions.
34 changes: 21 additions & 13 deletions chapter2/code/fits-bits.c
Original file line number Diff line number Diff line change
@@ -1,31 +1,39 @@
/*
* fit-bits.c
* fits-bits.c
*/
#include <stdio.h>
#include <assert.h>

int fits_bits(int x, int n) {
/*
* Assume w = 8, n = 3
* 1 <= n <= w
*
* assume w = 8, n = 3
* if x > 0
* 0b00000110 is ok, 0b00001010 is not
* first w-n bits must be 0
* 0b00000010 is ok, 0b00001010 is not, and 0b00000110 is not yet (thanks itardc@163.com)
* if x < 0
* 0b11111100 is ok, 0b10111100 is not, and 0b11111000 is not yet
* first w-n+1 bits must be 1
*
* the point is
* x << (w-n) >> (w-n) must be equal to x itself.
*
*/
int w = sizeof(int) << 3;
x >>= n - 1;
/*
* !(x >> 1) return 1 only when all bits are 0,
* !~x == 1 only when all bits are 1
*/
return !(x >> 1) || !~x;
int offset = w - n;
return (x << offset >> offset) == x;
}

int main(int argc, char* argv[]) {
assert(fits_bits(0xFF, 8));
assert(!fits_bits(0xFFFFFF00, 8));
assert(!fits_bits(0xFF, 8));
assert(!fits_bits(~0xFF, 8));

assert(fits_bits(0b0010, 3));
assert(!fits_bits(0b1010, 3));
assert(!fits_bits(0b0110, 3));

assert(fits_bits(~0b11, 3));
assert(!fits_bits(~0b01000011, 3));
assert(!fits_bits(~0b111, 3));
return 0;
}

Expand Down

0 comments on commit 4bddfa2

Please sign in to comment.