# 2018q3 Homework5 (bits) contributed by < [`dange0`](https://github.com/dange0) > ###### tags: `sysprog2018` ## 實做 ### absVal ```cpp int absVal(int x) { int y; y = x >> 31; return (x ^ y) - y; } ``` ### addOK ```cpp int addOK(int x, int y) { unsigned int x_msb, y_msb, sum_msb; y_msb = (y >> 31); x_msb = (x >> 31); sum_msb = ((x + y) >> 31); return (((x_msb ^ y_msb) + ((~(x_msb ^ y_msb)) & (~(x_msb ^ sum_msb)))) & 0x1); } ``` ### allEvenBits ```cpp int allEvenBits(int x) { x &= x >> 2; x &= x >> 4; x &= x >> 8; x &= x >> 16; return (x & 0x1); } ``` ### allOddBits ```cpp int allOddBits(int x) { x &= x >> 2; x &= x >> 4; x &= x >> 8; x &= x >> 16; return ((x >> 1) & 0x1); } ``` ### anyEvenBit ```cpp int anyEvenBit(int x) { x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return (x & 0x1); } ``` ### anyOddBit ```cpp int anyOddBit(int x) { x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return ((x >> 0x1) & 0x1); } ``` ### bang ```cpp int bang(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return (~x & 0x1); } ``` ### bitAnd ```cpp int bitAnd(int x, int y) { return ~(~x | ~y); } ``` ### bitCount ```cpp int bitCount(int x) { int mask1 = 0x55; int mask2 = 0x33; int mask3 = 0x0F; int mask4 = 0xFF; int mask5 = 0xFF; mask1 |= mask1 << 8; mask1 |= mask1 << 16; mask2 |= mask2 << 8; mask2 |= mask2 << 16; mask3 |= mask3 << 8; mask3 |= mask3 << 16; mask4 |= mask4 << 16; mask5 |= mask5 << 8; x = (x & mask1) + ((x >> 1) & mask1); x = (x & mask2) + ((x >> 2) & mask2); x = (x & mask3) + ((x >> 4) & mask3); x = (x & mask4) + ((x >> 8) & mask4); x = (x & mask5) + ((x >> 16) & mask5); return (x & mask5); } ``` 0101 0101 0101 0101 0101 0101 0101 0101 0011 0011 0011 0011 0011 0011 0011 0011 0000 1111 0000 1111 0000 1111 0000 1111 0000 0000 1111 1111 0000 0000 1111 1111 0000 0000 0000 0000 1111 1111 1111 1111 ### bitNor ```cpp int bitNor(int x, int y) { return ~x & ~y; } ``` ### bitOr ```cpp int bitOr(int x, int y) { return ~(~x & ~y); } ``` ### bitParity ```cpp int bitParity(int x) { x ^= x >> 1; x ^= x >> 2; x ^= x >> 4; x ^= x >> 8; x ^= x >> 16; return x & 0x1; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up