2023-10-03 23:08:19 +02:00
|
|
|
function hexToInt(hexNum) {
|
2024-05-25 13:01:13 +02:00
|
|
|
if (!/^[0-9A-F]+$/.test(hexNum)) {
|
|
|
|
|
throw new Error('Invalid hex string.')
|
|
|
|
|
}
|
2020-09-11 09:21:01 -03:00
|
|
|
const numArr = hexNum.split('') // converts number to array
|
2021-10-21 22:59:56 +05:30
|
|
|
return numArr.map((item, index) => {
|
|
|
|
|
switch (item) {
|
2023-10-03 23:08:19 +02:00
|
|
|
case 'A':
|
|
|
|
|
return 10
|
|
|
|
|
case 'B':
|
|
|
|
|
return 11
|
|
|
|
|
case 'C':
|
|
|
|
|
return 12
|
|
|
|
|
case 'D':
|
|
|
|
|
return 13
|
|
|
|
|
case 'E':
|
|
|
|
|
return 14
|
|
|
|
|
case 'F':
|
|
|
|
|
return 15
|
|
|
|
|
default:
|
|
|
|
|
return parseInt(item)
|
2021-10-21 22:59:56 +05:30
|
|
|
}
|
2020-09-11 09:21:01 -03:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-03 23:08:19 +02:00
|
|
|
function hexToDecimal(hexNum) {
|
2020-09-11 09:21:01 -03:00
|
|
|
const intItemsArr = hexToInt(hexNum)
|
|
|
|
|
return intItemsArr.reduce((accumulator, current, index) => {
|
2023-10-03 23:08:19 +02:00
|
|
|
return (
|
|
|
|
|
accumulator + current * Math.pow(16, intItemsArr.length - (1 + index))
|
|
|
|
|
)
|
2020-09-11 09:21:01 -03:00
|
|
|
}, 0)
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-25 13:01:13 +02:00
|
|
|
export { hexToDecimal }
|