判斷字元是否為 ASCII(0~127):
int __isascii(int c):窄字元版。int iswascii(wint_t c):寬字元版。void CheckCharAndPrint(char acChar) {
if(__isascii(acChar)) printf("char %c is ascii\n", acChar);
else printf("char %c not ascii\n", acChar);
}
void CheckWCharAndPrint(wchar_t awcChar) {
if(iswascii(awcChar)) wprintf(L"wchar %c is ascii\n", awcChar);
else { setlocale(LC_ALL,""); wprintf(L"wchar %c not ascii\n", awcChar); }
}
int _tmain() {
CheckCharAndPrint('a'); CheckCharAndPrint('中');
CheckWCharAndPrint(L'a'); CheckWCharAndPrint(L'中');
return 0;
}
| 平台 | __isascii | iswascii |
|---|---|---|
| MSVC | #define __isascii(_Char) ((unsigned)(_Char) < 0x80) | inline int __cdecl iswascii(wint_t _C) { return ((unsigned)(_C) < 0x80); } |
| GCC | #define __isascii(c) (((c) & ~0x7f) == 0) | 無(需自行實現) |
MSVC:強轉無號後比較 < 128。GCC:取反 0x7f 與字元位元 AND,檢查高位是否全 0。兩者邏輯等價,GCC 寫法更位運算風格。
測試代碼分別呼叫 MS 風格與 GCC 風格巨集,結果:**兩者效能幾乎相同**,GCC 偶爾快 0.1 秒但不穩定。結論:複雜位運算不一定比簡單比較快,現代編譯器優化極佳。
__toascii將字元轉為 ASCII(保留低 7 位):
#define __toascii(_Char) ((_Char) & 0x7f) // MSVC 與 GCC 實現相同
GCC 註釋 mask off high bits。此實現與 GCC __isascii 前半段邏輯一致(保留低 7 位 vs 檢查高位為 0)。
__isascii 可能在特定驗證場景有用。