在寫C語言上機題時遇到一行代碼是
word[i] |= 0x20;
| 是“按位與”的意思
|= 就是按位與後賦值
0x20 是十六進制,轉換爲十進制是32,即ASCII碼爲32的空格
完整的函數如下:
bool is_the(char word[15]) //判斷word是否爲"the"
{
char the[] = "the";
if (strlen(word) != strlen(the))
return false;
for (int i = 0; i < strlen(word); i++)
word[i] |= 0x20;
return strcmp(word, the) == 0;
}
實現的功能是:
對每個字符轉換爲小寫字母。如word[i]爲'T'時,ASCII碼爲84,轉換爲二進制1010100 。與0x20即二進制爲10000進行按位與。得到1110100,轉換爲十進制是116,對應的ASCII碼爲't'。