# Read (bitwise) [你所不知道的 C 語言: bitwise 操作](https://hackmd.io/@sysprog/c-bitwise) ## allEvenBits 目標:回傳是否所有偶數位皆為 1 `int` 32-bits integer ### 實作 ``` c= int allEvenBits(int x) { x = x & (x>>16); //前 16 位變成 0, 後 16 位是對折結果 x = x & (x>>8); //前 24 位變成 0, 後 8 位是對折結果 x = x & (x>>4); //前 28 位變成 0, 後 4 位是對折結果 x = x & (x>>2); //前 30 位變成 0, 後 2 位是對折結果 /* If all even-bits are 1, by now, the second bit should be 1.*/ return x & 0x03; } ``` Question: 我的理解做完 3-6 行操作,`x` 應該對折到剩下第一、二位還有數值,偶數位元對折的結果應該是第二位 我看其他人寫都是`return x & 0x01;` 我腦袋轉不過來 whyy?? [2018q3 Homework (bits)](https://hackmd.io/@ofAlpaca/By9Rt6x37?type=view#allEvenBits) [2018q3 Homework (bits)](https://hackmd.io/@siahuat0727/Bkf4Ei0oQ?type=view) 回: :::info [Bits - Least-Significant/Lowest is 0th or 1st; zero or one indexed](https://softwareengineering.stackexchange.com/questions/315117/bits-least-significant-lowest-is-0th-or-1st-zero-or-one-indexed) 位元是==0(LSB) ~ 32(MSB)== ::: 修正後是 ``` c= int allEvenBits(int x) { x = x & (x>>16); //前 16 位變成 0, 後 16 位是對折結果 x = x & (x>>8); //前 24 位變成 0, 後 8 位是對折結果 x = x & (x>>4); //前 28 位變成 0, 後 4 位是對折結果 x = x & (x>>2); //前 30 位變成 0, 後 2 位是對折結果 /* If all even-bits are 1, by now, the first bit should be 1.*/ return x & 0x01; } ``` --- ## [Flip bitmask horizontally [duplicate] - stack overflow](https://stackoverflow.com/questions/40652691/flip-bitmask-horizontally?fbclid=IwAR0LZKYqSz1VePbhGFga4IW351LrF_OllBAOQunFnpJ2VpstG2GorxUjY80) ``` c= /* Reverse 16-bit unsigned integer */ /* 取 x 的偶數位元左移 1 到奇數位元 * 取 x 的奇數位元(>>1) ==> 奇偶對調*/ x = ((x & 0x5555) << 1) | ((x >> 1) & 0x5555); // swap bits /* 兩兩對調 */ x = ((x & 0x3333) << 2) | ((x >> 2) & 0x3333); // swap 2-bit pieces /* 4bits對調 */ x = ((x & 0x0f0f) << 4) | ((x >> 4) & 0x0f0f); // swap nibbles return (x >> 8) | (x << 8); // optimized last step ``` nibble (n.) 一點, 蠶食 ---