hex.js
1.16 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
'use strict';
var Enc = require('./bytes.js');
// To Hex
Enc.bufToHex = function(u8) {
var hex = [];
var i, h;
var len = u8.byteLength || u8.length;
for (i = 0; i < len; i += 1) {
h = u8[i].toString(16);
if (2 !== h.length) {
h = '0' + h;
}
hex.push(h);
}
return hex.join('').toLowerCase();
};
Enc.numToHex = function(d) {
d = d.toString(16); // .padStart(2, '0');
if (d.length % 2) {
return '0' + d;
}
return d;
};
Enc.strToHex = function(str) {
return Enc._binToHex(Enc.strToBin(str));
};
Enc._binToHex = function(bin) {
return bin
.split('')
.map(function(ch) {
var h = ch.charCodeAt(0).toString(16);
if (2 !== h.length) {
h = '0' + h;
}
return h;
})
.join('');
};
// From Hex
Enc.hexToBuf = function(hex) {
var arr = [];
hex.match(/.{2}/g).forEach(function(h) {
arr.push(parseInt(h, 16));
});
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
};
Enc.hexToStr = function(hex) {
return Enc.binToStr(_hexToBin(hex));
};
function _hexToBin(hex) {
return hex.replace(/([0-9A-F]{2})/gi, function(_, p1) {
return String.fromCharCode('0x' + p1);
});
}
Enc._hexToBin = _hexToBin;
module.exports = Enc;