-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathutil.js
62 lines (55 loc) · 1.3 KB
/
util.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
import RNFetchBlob from 'rn-fetch-blob'
/**
*
* @param {String} hex Hex encoded string
* @return bytes (of type Uint8Array)
*/
function hex2bytes(hex) {
//console.log("begin hex2bytes");
if (!hex) {
return null;
}
let bytes = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
}));
//console.log("end hex2bytes");
return bytes;
}
/**
*
* @param {Uint8Array} bytes
* @return Hex encoded string
*/
function bytes2hex(bytes) {
if (!bytes) {
return null;
}
return Array.prototype.map.call(bytes, x => ('00' + x.toString(16)).slice(-2)).join('');
}
/**
* @param {*} bytes Uint8Array
*/
function bytesToBase64(bytes) {
// Uint8Array to string the scalable way
let binstr = Array.prototype.map.call(bytes, function (ch) {
return String.fromCharCode(ch);
}).join('');
// btoa
return RNFetchBlob.base64.encode(binstr);
}
function base64ToBytes(base64) {
// atob
let binstr = RNFetchBlob.base64.decode(base64);
// str to binary
let bytes = new Uint8Array(binstr.length);
Array.prototype.forEach.call(binstr, function (ch, i) {
bytes[i] = ch.charCodeAt(0);
});
return bytes;
}
export default {
hex2bytes,
bytes2hex,
bytesToBase64,
base64ToBytes
}