Previously, because of the needs of the project, we need to convert the string with Chinese into byte array and image data, and then pass it to the server side with binary data.
Before, see online has the use of Array.prototype.map.call (str, function (c) {return c.charcodeat (0);}) Method converts a string into a byte array, but the measured results indicate that the method implements the following functions:
1. If the character is a single-byte character, it is represented by a value less than 128.
2. If the character is a double-byte character, such as Chinese, it is represented by a value greater than 256.
According to the test results, this method simply converts the string into a Unicode encoded array, not a byte array.
Therefore, it is also necessary to convert the values in the resulting array into double-byte representations. The specific code is as follows:
var str = "Conversion test data"; var arr = Array.prototype.map.call (str, function (c) {return c.charcodeat (0);}); arr = ToUTF16 (arr); function ToUTF16 (arr) { var result = new Array (); var k = 0; for (var i = 0; i < arr.length; i++) { result[k++] = arr[i] & 0xFF; result[k++] = arr[i] >> 8; } return result;}
Based on the above experience, the code to convert Chinese into UTF16 and UTF8 is as follows, tested in Google Chrome.
function ToUTF16 (str) { var result = new Array (); var k = 0; for (var i = 0; i < str.length; i++) { var j = str[i].charcodeat (0); result[k++] = j & 0xFF; result[k++] = j >> 8; } return result;} function ToUTF8 (str) { var result = new Array (); var k = 0; for (var i = 0; i < str.length; i++) { var j = encodeURI (Str[i]); if (j.length==1) { //non-converted characters result[k++] = j.charcodeat (0); } else { //Convert to%xx form of the character var bytes = J.split ("%"); for (var L = 1; l < bytes.length; l++) { result[k++] = parseint ("0x" + bytes[l]); }} return result;}
How JavaScript converts Chinese Unicode16 byte arrays