repl.it
@SagaciousPan/

Converting a Hexadecimal to Decimal.

Nodejs

- Convert a hexadecimal number to decimal number.

fork
loading
Files
  • index.js
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
/* -- HEX SYSTEM -- */
/* Hex, or hexadecimal, is a number system of base 16. This number system is especially interesting because in our casually used decimal system we have only 10 digits to represent numbers. As hex system has 16 digits, the extra needed 6 digits are represented by the first 6 letters of English alphabet. Hence, hex digits are 0,1,2,3,4,5,6,7,8 and 9 A, B, C, D, E, F. This number system is the most commonly used in mathematics and information technologies. I.e. in html programming colors can be represented by a 6-digit hexadecimal number: FFFFFF represents white, 000000 represents black, and so on. 

Hex is a base 16 number and decimal is a base 10 number.
We need to know the decimal equivalent of every hex number digit.
Here are the steps to convert hex to decimal:

 - STEP 01: Get the decimal equivalent of hex from table.
 - STEP 02: Multiply every digit with 16 power of digit location. 
 - STEP 03: Sum all the multipliers.

  — https://www.binaryhexconverter.com/hex-to-decimal-converter */

/* Hexadecimal : 0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  */
/* Decimal     : 0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 */

/* Extended Chart */

/* Hexadecimal : 17 18 19 ... 1A 1B 1C ... 20 21 22 ... 2A 2B 2C */
/* Decimal     : 11 12 13 ... 26 27 28 ... 32 33 34 ... 42 43 44 */

/* ############################################################# */

function hexadecimalToDecimal () {
  /* this is the hexadecimal that we will be converting */
  var hexadecimal = "FFFFFF";
  /* in order to follow step 02 we need to save the length of the hexadecimal */
  var len = hexadecimal.length;
  var func = "";
  console.log("hexadecimal: "+hexadecimal+"\n");
  do {
    var reversedHex = hexadecimal.split("").reverse().join("");
    console.log("hexadecimal number: "+reversedHex[len-1]+"; exponent: "+(len-1)+";\n  use: ("+reversedHex[len-1]+"*16^("+(len-1)+"))");
    len--;
    func += "("+reversedHex[len]+"*16**("+(len)+"))";
    if(len>0){
      func += "+";
    } else {
      console.log("\nfunction:\n  "+func);
      func = func.replace(/(A)/g,"10");
      func = func.replace(/(B)/g,"11");
      func = func.replace(/(C)/g,"12");
      func = func.replace(/(D)/g,"13");
      func = func.replace(/(E)/g,"14");
      func = func.replace(/(F)/g,"15");
      console.log("\nfunction after letters replaced:\n  "+func+"\n\ndecimal number:\n  "+eval(func));
    }
  } while(len>0);
  console.log("\n  By SagaciousPan");
} hexadecimalToDecimal();