---
tags: sysprog2020
---
# 2020q3 Homework2 (quiz2)
contributed by < `mingjer` >
# 測驗 `1`
```cpp=
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
bool is_ascii(const char str[], size_t size)
{
if (size == 0)
return false;
int i = 0;
while ((i + 8) <= size) {
uint64_t payload;
memcpy(&payload, str + i, 8);
if (payload & MMM)
return false;
i += 8;
}
while (i < size) {
if (str[i] & 0x80)
return false;
i++;
}
return true;
}
```
> * `MMM` = `0x8080808080808080`
> * 因為從比對 1 個 byte 變成 8 個 bytes,所以將 `0x80` 擴充為 `0x8080808080808080` 即可
# 測驗 `2`
```cpp=
uint8_t hexchar2val(uint8_t in)
{
const uint8_t letter = in & MASK;
const uint8_t shift = (letter >> AAA) | (letter >> BBB);
return (in + shift) & 0xf;
}
```
> * `MASK` = `0x40`
> * `letter` 是為了判斷輸入是否為英文字母,從 ASCII 表格中我們可以發現數字不會使用到 0==0==11 0000 這個位置 bit,所以可以推論 `MASK` 為 `0x40`
> * `AAA` = `3`
> * `BBB` = `6`
> * 從 A (0100 0001) 和 a (0110 0001),兩者最終輸出都為10 (0000 1010),因為會 `&0xf`,所以我們只要觀察末四位,(`0001` + `shift`) & `1111` = `1010`,推出答案為`0101`
# 測驗 `3`
# 測驗 `4`
```cpp=
bool divisible(uint32_t n)
{
return n * M <= YYY;
}
```
# 測驗 `5`
# 測驗 `6`