PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How to convert hex to decimal WITH A LOOP in JavaScript

 August 10, 2022     decimal, hex, javascript, loops, typescript     No comments   

Issue

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?


Solution

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'));



Answered By - trincot
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing