首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 執行期庫函數 __isascii、iswascii、__toascii 深度解析與實現對比

     編輯:關於C語言

函數用途

判斷字元是否為 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;
}

實現原理對比

平台__isasciiiswascii
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 寫法更位運算風格。

效能測試(10 億次呼叫)

測試代碼分別呼叫 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)。

個人感想

  • 這兩函數實務極少用到:ASCII 字元本身無需轉換,非 ASCII 轉後原意喪失;__isascii 可能在特定驗證場景有用。
  • MSVC CRT 源碼無註釋,GCC 註釋豐富——開源碼確實更利於學習分析。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved