大多數文本編輯器,都會在文本文件的頭部插入一部分特殊的字節,用于輔助文本編輯器來判斷該文件的字符集編碼類型。
如:記事本
目前支持的字符集類型,通常為三種:
Unicode、UTF8、UnicodeBIG、CP_ACP(默認編碼,簡體中文一般為:GBK)
int File::GetEncoding(const void* p, int length, int& offset) noexcept {offset = 0;if (NULL == p || length < 3) {return ppp::text::Encoding::ASCII;}// byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };// byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };// byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; // BOMconst Byte* s = (Byte*)p;if (s[0] == 0xEF && s[1] == 0xBB && s[2] == 0xBF) {offset += 3;return ppp::text::Encoding::UTF8;}elif(s[0] == 0xFE && s[1] == 0xFF && s[2] == 0x00) {offset += 3;return ppp::text::Encoding::BigEndianUnicode;}elif(s[0] == 0xFF && s[1] == 0xFE && s[2] == 0x41) {offset += 3;return ppp::text::Encoding::Unicode;}else {return ppp::text::Encoding::ASCII;}}