Utils.js
1.3 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
'use strict';
const int2Bytes = function(count) {
const byteArr = [ (count >> 24 & 255), (count >> 16 & 255), (count >> 8 & 255), (count & 255) ];
// console.log(`debug int2Bytes: ${count} -> ${byteArr}`);
return byteArr;
};
const bytes2int = function(byteArr) {
let count = 0;
for (let i = 0; i < 4; ++i) {
count <<= 8;
count |= byteArr[i] & 255;
}
// console.log(`debug bytes2int: ${byteArr} -> ${count}`);
return count;
};
// https://stackoverflow.com/questions/3195865/converting-byte-array-to-string-in-javascript
const string2Bin = function(str) {
const binaryArr = [];
for (let i = 0; i < str.length; i++) {
binaryArr.push(str.charCodeAt(i));
}
// console.log(`debug string2Bin: ${str} -> ${binaryArr}`);
return binaryArr;
};
const bin2String = function(array) {
const str = String.fromCharCode.apply(String, array);
// console.log(`debug bin2String: ${array} -> ${str}`);
return str;
};
const getRandomStr = function(size) {
const base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let randomStr = '';
for (let i = size; i > 0; --i) {
randomStr += base[Math.floor(Math.random() * base.length)];
}
return randomStr;
};
module.exports = {
int2Bytes,
bytes2int,
string2Bin,
bin2String,
getRandomStr,
};