-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (77 loc) · 1.97 KB
/
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
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
/**
* Convert hexadecimal string to number array
*
* @param {string} hexString hexadeciaml string to be converted
*/
export function hexToArray(hexString) {
let hexStr = hexString.replace(/\s/g, "").toUpperCase();
if (hexStr.length % 2 != 0) {
hexStr = "0" + hexStr;
}
let arr = [];
for (let i = 0; i < hexStr.length; i += 2) {
let item = hexStr.slice(i, i + 2);
arr.push(parseInt(item, 16));
}
return arr;
}
/**
* Convert number or number array to hexadecimal string
*
* @param {number|number[]} input number or number array to be converted
*/
export function toHex(input) {
if (Array.isArray(input)) {
return arrayToHex(input);
}
else {
return numberToHex(input);
}
}
/**
* convert number array to hexadecimal string
*
* @param {number[]} arr number array to be converted
*/
export function arrayToHex(arr) {
let hexString = "";
for (let i = 0; i < arr.length; i++) {
let hexValue = numberToHex(arr[i]);
hexString += hexValue;
}
return hexString.toUpperCase();
}
/**
* Convert number to hexadecimal string
*
* @param {number} num number to be converted
*/
export function numberToHex(num) {
let hex = num.toString(16).toUpperCase();
return hex.length % 2 == 1 ? "0" + hex : hex;
}
/**
* Convert hexadecimal string to signed number
*
* @param {string} hex hexadecimal string to be converted
*/
export function hexToSignedNumber(hex) {
if (hex.length % 2 != 0) {
hex = "0" + hex;
}
let num = parseInt(hex, 16);
let maxVal = Math.pow(2, (hex.length / 2) * 8); // 1字节 256
if (num > maxVal / 2 - 1) {
// 1字节有符号能表示的最大值:256/2-1=127
num = num - maxVal; // 大于 127 说明最高位为1,即为负数
}
return num;
}
/**
* Convert hexadecimal string to number
*
* @param {string} hex hexadecimal string to be converted
*/
export function hexToNumber(hex) {
return parseInt(hex, 16);
}