forked from zhangshiqian1214/sproto-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
netutils.js
97 lines (81 loc) · 2.6 KB
/
netutils.js
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
var netutils = (function() {
var t = {};
t.array2arraybuffer = function(array) {
var b = new ArrayBuffer(array.length);
var v = new DataView(b, 0);
for (var i = 0; i < array.length; i++) {
v.setUint8(i, array[i]);
}
return b;
}
t.arraybuffer2array = function(buffer) {
var v = new DataView(buffer, 0);
var a = new Array();
for (var i = 0; i < v.byteLength; i++) {
a[i] = v.getUint8(i);
}
return a;
}
t.string2utf8 = function(str) {
var back = [];
var byteSize = 0;
for (var i = 0; i < str.length; i++) {
var code = str.charCodeAt(i);
if (0x00 <= code && code <= 0x7f) {
byteSize += 1;
back.push(code);
} else if (0x80 <= code && code <= 0x7ff) {
byteSize += 2;
back.push((192 | (31 & (code >> 6))));
back.push((128 | (63 & code)))
} else if ((0x800 <= code && code <= 0xd7ff) || (0xe000 <= code && code <= 0xffff)) {
byteSize += 3;
back.push((224 | (15 & (code >> 12))));
back.push((128 | (63 & (code >> 6))));
back.push((128 | (63 & code)))
}
}
for (i = 0; i < back.length; i++) {
back[i] &= 0xff;
}
return back;
};
t.utf82string = function(arr) {
if (typeof arr === 'string') {
return null;
}
var UTF = '';
for (var i = 0; i < arr.length; i++) {
if (arr[i] == null) {
break;
}
var one = arr[i].toString(2);
var v = one.match(/^1+?(?=0)/);
if (v && one.length == 8) {
var bytesLength = v[0].length;
var store = arr[i].toString(2).slice(7 - bytesLength);
for (var st = 1; st < bytesLength; st++) {
store += arr[st + i].toString(2).slice(2);
}
UTF += String.fromCharCode(parseInt(store, 2));
i += bytesLength - 1;
} else {
UTF += String.fromCharCode(arr[i]);
}
}
return UTF;
};
t.arrayconcat = function(a1, a2) {
var b = new Array();
for (var i = 0; i < a1.length; i++) {
b[i] = a1[i];
}
for (var j = a1.length; j < a1.length + a2.length; j++) {
b[j] = a2[j - a1.length];
}
return b;
};
return t;
}());
// export default netutils;
module.exports = netutils;