-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwaibibabo.js
117 lines (109 loc) · 2.6 KB
/
waibibabo.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
function bin2Waibi(num) {
switch (num) {
case 0b00:
return '歪';
case 0b01:
return '比';
case 0b10:
return '巴';
case 0b11:
return '卜';
default:
return null;
}
}
function waibi2Bin(waibi) {
switch (waibi) {
case '歪':
return 0b00;
case '比':
return 0b01;
case '巴':
return 0b10;
case '卜':
return 0b11;
default:
return null;
}
}
function waibiEncode(text) {
return new Promise(((resolve, reject) => {
let reader = new FileReader();
reader.onloadend = () => {
const textArray = new Uint8Array(reader.result);
let waibiText = [];
for (let t of textArray) {
let bin;
// 7,6
bin = t >>> 6;
waibiText.push(bin2Waibi(bin));
// 5,4
bin = (t >>> 4) & 0b11;
waibiText.push(bin2Waibi(bin));
// 3,2
bin = (t >>> 2) & 0b11;
waibiText.push(bin2Waibi(bin));
// 1,0
bin = t & 0b11;
waibiText.push(bin2Waibi(bin));
}
waibiText = waibiText.join('');
resolve(waibiText);
};
reader.onerror = reject;
reader.readAsArrayBuffer(new Blob([text], {type: 'text/plain'}));
}));
}
function waibiDecode(waibiText) {
return new Promise(((resolve, reject) => {
if (waibiText.length % 4 !== 0) {
throw Error('歪比巴卜密文长度必须为4的倍数');
}
waibiText = waibiText.split('');
let dataArray = [];
let move = 6;
let temp = 0;
for (let waibi of waibiText) {
let a = waibi2Bin(waibi);
if (a == null) {
throw Error('歪比巴卜密文中只允许出现"歪比巴卜"四个字');
}
temp += a << move;
move -= 2;
if (move < 0) {
dataArray.push(temp);
temp = 0;
move = 6;
}
}
let typedArray = new Uint8Array(dataArray);
let reader = new FileReader();
reader.readAsText(new Blob([typedArray.buffer], {type: 'application/octet-stream'}));
reader.onloadend = () => {
resolve(reader.result);
};
reader.onerror = reject;
}));
}
window.onload = () => {
$('#btn-encode').click(event => {
let text = $('#text')[0].value;
if (text.length > 0) {
waibiEncode(text).then(result => {
$('#waibi')[0].value = result;
}).catch(error => {
alert(error);
});
}
});
$('#btn-decode').click(event => {
let text = $('#waibi')[0].value;
if (text.length > 0) {
waibiDecode(text).then(result => {
$('#text')[0].value = result;
}).catch(error => {
alert(error);
});
}
});
};