From 1a3a2639ba8381a5b22cbb15c4a9507c841e2394 Mon Sep 17 00:00:00 2001 From: Higor Castilho Date: Fri, 11 Sep 2020 09:21:01 -0300 Subject: [PATCH] Create HexToDecimal.js Hello. Hope this can be useful to conversions in JavaScript repository :) --- Conversions/HexToDecimal.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Conversions/HexToDecimal.js diff --git a/Conversions/HexToDecimal.js b/Conversions/HexToDecimal.js new file mode 100644 index 0000000000..8627dbcf7d --- /dev/null +++ b/Conversions/HexToDecimal.js @@ -0,0 +1,27 @@ +function hexToInt (hexNum) { + const numArr = hexNum.split('') // converts number to array + numArr.map((item, index) => { + if (!(item > 0)) { + switch (item) { + case 'A': return (numArr[index] = 10) + case 'B': return (numArr[index] = 11) + case 'C': return (numArr[index] = 12) + case 'D': return (numArr[index] = 13) + case 'E': return (numArr[index] = 14) + case 'F': return (numArr[index] = 15) + } + } else numArr[index] = parseInt(item) + }) + return numArr // returns an array only with integer numbers +} + +function hexToDecimal (hexNum) { + const intItemsArr = hexToInt(hexNum) + return intItemsArr.reduce((accumulator, current, index) => { + return accumulator + (current * Math.pow(16, (intItemsArr.length - (1 + index)))) + }, 0) +} + +// test cases +console.log(hexToDecimal('5DE9A')) // 384666 +console.log(hexToDecimal('3D')) // 61