# 2022q1 Homework3 (quiz3) contributed by < `a12345645` > ## 測驗1 ```c #define GENMASK(h, l) \ (((~0UL) >> (LEFT)) & ((~0UL) >> (l) << (RIGHT))) ``` `LEFT` = `63 - h` `RIGHT` = `l` - `~0UL` 為所有位元皆為 `1` - `(~0UL) >> (63 - h)` 為最低位元到第 `h` 位元皆為 `1` - `(~0UL) >> (l) << (RIGHT))` 為第 `l` 到最高位元都為 `1` - 最後在把兩個做 AND 運算得到 mask ## 測驗 2 ```c struct foo; struct fd { struct foo *foo; unsigned int flags; }; enum { FOO_DEFAULT = 0, FOO_ACTION, FOO_UNLOCK, } FOO_FLAGS; static inline struct fd to_fd(unsigned long v) { return (struct fd){EXP1, v & 3}; } ``` 要將 `v` 對 4 個位元組進行向下對齊 代表要清除 `v` 的最後兩個位元 所以是 `v & ~3` `EXP1` = `v & ~3` ## 測驗 3 ```c #include <stdint.h> uint8_t rev8(uint8_t x) { x = (x >> 4) | (x << 4); x = ((x & 0xCC) >> 2) | (EXP2); x = ((x & 0xAA) >> 1) | (EXP3); return x; } ``` `EXP2` = `0x33` `EXP3` = `0x55` 舉例原本為 01101010 1. 第一行 `x = (x >> 4) | (x << 4)` 把前 4 個 bits 與後 4 個 bits對調 0110 | 1010 1010 | 0110 2. 第二行 `x = ((x & 0xCC) >> 2) | (0x33)` 對調後的分成兩個兩個一組在對調 10 | 10 | 01 | 10 10 | 10 | 10 | 01 3. 最後再兩兩對調 1 | 0 | 1 | 0 | 1 | 0 | 0 | 1 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0
×
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