3

Is it possible to convert a hex number to a decimal number with a loop?

Example: input "FE" output "254"

I looked at those questions :

How to convert decimal to hex in JavaScript?

Writing a function to convert hex to decimal Writing a function to convert hex to decimal

Writing a function to convert hex to decimal

How to convert hex to decimal in R

How to convert hex to decimal in c#.net?

And a few more that were not related to JS or loops. I searched for a solution in other languages too in case that I find a way to do it,but I didn't. The first one was the most useful one. Maybe I can devide by 16,compare the result to preset values and print the result, but I want to try with loops. How can I do it?

Community
  • 1
  • 1
  • 1
    too many answers here, what are some restrictions? Can you use parseInt? because it just gives the answer and you can put it into loop :) for(;;) {return parseInt(hex,16);} – danchik Nov 08 '16 at 20:43

5 Answers5

6

Maybe you are looking for something like this, knowing that it can be done with a oneliner (with parseInt)?

function hexToDec(hex) {
    var result = 0, digitValue;
    hex = hex.toLowerCase();
    for (var i = 0; i < hex.length; i++) {
        digitValue = '0123456789abcdef'.indexOf(hex[i]);
        result = result * 16 + digitValue;
    }
    return result;
}

console.log(hexToDec('FE'));

Alternative

Maybe you want to have a go at using reduce, and ES6 arrow functions:

function hexToDec(hex) {
    return hex.toLowerCase().split('').reduce( (result, ch) =>
        result * 16 + '0123456789abcdefgh'.indexOf(ch), 0);
}

console.log(hexToDec('FE'));
trincot
  • 317,000
  • 35
  • 244
  • 286
1

Just another way to do it...

// The purpose of the function is to convert Hex to Decimal.  
// This is done by adding each of the converted values.
function hextoDec(val) {
  
    // Reversed the order because the added values need to 16^i for each value since 'F' is position 1 and 'E' is position 0
    var hex = val.split('').reverse().join('');
  
    // Set the Decimal variable as a integer
    var dec = 0;
  
    // Loop through the length of the hex to iterate through each character
    for (i = 0; i < hex.length; i++) {
      
        // Obtain the numeric value of the character A=10 B=11 and so on..
        // you could also change this to var conv = parseInt(hex[i], 16) instead
        var conv = '0123456789ABCDEF'.indexOf(hex[i]);
      
        // Calculation performed is the converted value * (16^i) based on the position of the character
        // This is then added to the original dec variable.  'FE' for example
        // in Reverse order [E] = (14 * (16 ^ 0)) + [F] = (15 * (16 ^ 1)) 
        dec += conv * Math.pow(16, i);
      
    }
  
    // Returns the added decimal value
    return dec;
}

console.log(hextoDec('FE'));
Robert Lee
  • 1,541
  • 1
  • 10
  • 20
0

If you want to loop over every hex digit, then just loop from end to beginning, shifting each digit 4 bits to the left as you add them (each hex digit is four bits long):

function doit(hex) {
    var num = 0;
    for(var x=0;x<hex.length;x++) {
        var hexdigit = parseInt(hex[x],16);
        num = (num << 4) | hexdigit;
    }
    return num;
}
danchik
  • 181
  • 10
  • This also assumes hex is given as a string, if not then first do `hex = hex.toString(16)` – danchik Nov 08 '16 at 20:53
  • what would be the use of calling a function with a decimal number, have the function convert it to a hex string internally, and let it decode it again into the same decimal number that was passed to the function in the first place? – trincot Nov 08 '16 at 20:57
  • right :) just wanted make sure passed in type wouldn't cause an exception – danchik Nov 08 '16 at 21:01
0

Sorry that was backwards, and I can't find where to edit answer, so here is corrected answer:

function doit(hex) {
    var num = 0;
    for(var x=0;x<hex.length;x++) {
        var hexdigit = parseInt(hex[x],16);
        num = (num << 4) | hexdigit;
    }
    return num;
}
danchik
  • 181
  • 10
  • There is an [edit](http://stackoverflow.com/posts/40496196/edit) link below your answer. – trincot Nov 08 '16 at 21:07
  • yep, but once I added the comment, the Edit of the answer was no longer there, only for comment, until I left and reloaded the page, strange – danchik Nov 08 '16 at 21:10
0

JavaScript can natively count in hex. I'm finding out the hard way that, in a loop, it converts hex to decimal, so for your purposes, this is great.

prepend your hex with 0x , and you can directly write a for loop.

For example, I wanted get an array of hex values for these unicode characters, but I am by default getting an array of decimal values.

Here's sample code that is converting unicode hex to dec

    var arrayOfEmojis = [];

    // my range here is in hex format
    for (var i=0x1F600; i < 0x1F64F; i++) {
        arrayOfEmojis.push('\\u{' + i + '}');
    }

    console.log(arrayOfEmojis.toString()); // this outputs an array of decimals
Eleanor Zimmermann
  • 414
  • 1
  • 8
  • 26