-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (42 loc) · 858 Bytes
/
index.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
/**
* @param {number} num
* @return {string}
*/
const toHex = function (num) {
if (num === 0) {
return '0';
}
let partStack = [];
for (let i = 0; i < 8; ++i) {
partStack.push(num & 0xf);
num >>= 4;
}
let ret = '';
while (partStack.length > 0) {
let part = partStack.pop();
if (part === 0 && ret.length === 0) {
continue;
}
ret = ret + hexCharacter(part);
}
return ret;
};
function hexCharacter(num) {
switch (num) {
case 10:
return 'a';
case 11:
return 'b';
case 12:
return 'c';
case 13:
return 'd';
case 14:
return 'e';
case 15:
return 'f';
default:
return num.toString();
}
}
module.exports = toHex;