At first, we used ASCII encoding to read text data and simulate binary data reading. However, we found that if the character encoding is greater than 127, we only get a value smaller than 128, which is equivalent to getting more than 128, therefore, ASCII encoding is not acceptable.
Continue searching. Find an article "Reading And Writing Binary Files Using JScript" in CodeProejct.com, which contains exactly what I need.
In fact, it is also easy to say, that is, to change the encoding and use 437. This is an extended ASCII code developed by IBM, which also makes use of the highest bit of the ASCII code, extend the number of characters in the character set from 128 to 256, and the character data read using this character set is equivalent to the original binary data.
After the obstacle is solved, it is necessary to identify the file encoding by using ADODB. stream object to read the first two bytes of the file, and then based on the two bytes, you can determine what the file encoding is.
If the UTF-8 file contains BOM, the first two bytes are 0xEF, 0xBB, and for example, the first two bytes of the Unicode file are 0xFF, 0xFE, these are the basis for determining the file encoding.
Note that in ADODB. stream does not have a one-to-one correspondence when reading characters. That is to say, if the binary data is 0xEF, the character read after charCodeAt is not 0xFE, but another value, the corresponding table can be found in the article above.
Program code:
Copy codeThe Code is as follows:
Function CheckEncoding (filename ){
Var stream = new ActiveXObject ("ADODB. Stream ");
Stream. Mode = 3;
Stream. Type = 2;
Stream. Open ();
Stream. Charset = "437 ";
Stream. LoadFromFile (filename );
Var bom = escape (stream. ReadText (2 ));
Switch (bom ){
// 0xEF, 0xBB => UTF-8
Case "% u2229 % u2557 ":
Encoding = "UTF-8 ";
Break;
// 0xFF, 0xFE => Unicode
Case "% A0 % u25A0 ":
// 0xFE, 0xFF => Unicode big endian
Case "% u25A0 % A0 ":
Encoding = "Unicode ";
Break;
// GBK is used if it cannot be determined, so that Chinese characters can be correctly processed in most cases.
Default:
Encoding = "GBK ";
Break;
}
Stream. Close ();
Delete stream;
Stream = null;
Return encoding;
}
In this way, you can obtain the file encoding by calling the CheckEncoding function as needed.
I hope this article will help you.