-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutf.js
More file actions
63 lines (61 loc) · 2.23 KB
/
utf.js
File metadata and controls
63 lines (61 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
(function(exports) {'use strict';
function utf16to8(str) {
var out, i, len, c, c1;
out = "";
len = str.length;
for (i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if(c >= 0xd800 && c < 0xdc00 && (c1 = str.charCodeAt(1+i)) >= 0xdc00 && c1 < 0xe000) {
c = (((c & 0x3ff) << 10) | (c1 & 0x3ff)) + 0x10000;
out += String.fromCharCode(0xF0 | ((c >> 18) & 0x07));
out += String.fromCharCode(0x80 | ((c >> 12) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
++i;
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}
function utf8to16(str) {
var out, i, len, c;
var char2, char3, char4;
out = "";
len = str.length;
i = 0;
while (i < len) {
c = str.charCodeAt(i++);
switch (c >> 4) {
case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:
out += str.charAt(i - 1);
break;
case 12:case 13:
char2 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
char2 = str.charCodeAt(i++);
char3 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | (char3 & 0x3F));
break;
case 15:
char2 = str.charCodeAt(i++);
char3 = str.charCodeAt(i++);
char4 = str.charCodeAt(i++);
out += String.fromCodePoint(((c & 0x07) << 18) | ((char2 & 0x3F) << 12) | ((char3 & 0x3F) << 6) | (char4 & 0x3F));
break;
}
}
return out;
}
exports.utf16to8 = utf16to8;
exports.utf8to16 = utf8to16;
})(window);