ArrayBufferUtil.js
2.2 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
export default class ArrayBufferUtil {
static ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
static str2ab(str) {
let buf = new ArrayBuffer(str.length * 2); // one char use 2 byte
let bufView = new Uint16Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
static strToUint8Array(str) {
let out, i, len, c;
out = "";
len = str.length;
let uintArray = [];
for (i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
uintArray.push(c);
} else if (c > 0x07FF) {
uintArray.push(0xE0 | ((c >> 12) & 0x0F));
uintArray.push(0x80 | ((c >> 6) & 0x3F));
uintArray.push(0x80 | ((c >> 0) & 0x3F));
//out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
//out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
//out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
uintArray.push(0xC0 | ((c >> 6) & 0x1F));
uintArray.push(0x80 | ((c >> 0) & 0x3F));
//out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
//out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return new Uint8Array(uintArray);
}
static uint8ArrayToStr(uint8, index) {
let out, i, len, c;
let char2, char3;
out = "";
len = uint8.buffer.byteLength;
i = uint8.offset + index; //pzm update 前两个字符乱码
while (i < uint8.limit) {
c = uint8.view[i++];
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
out += String.fromCharCode(uint8.view[i - 1]);
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
char2 = uint8.view[i++];
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = uint8.view[i++];
char3 = uint8.view[i++];
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}
return out;
}
}