首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在JavaScript中用循环将十六进制转换为十进制

如何在JavaScript中用循环将十六进制转换为十进制
EN

Stack Overflow用户
提问于 2016-11-09 04:29:33
回答 5查看 8.6K关注 0票数 2

是否可以使用循环将十六进制数转换为十进制数?

示例:输入"FE“输出"254”

我看了看这些问题:

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?

还有一些与JS或循环无关的内容。我也在寻找其他语言的解决方案,以防我找到一种方法来做,但我没有做到,第一个是最有用的。也许我可以除以16,将结果与预设值进行比较,然后打印结果,但我想尝试使用循环。我该怎么做呢?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-11-09 04:52:37

也许你正在寻找这样的东西,知道它可以用一个线条(用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'));

替代方案

也许你想尝试使用reduce和ES6 arrow functions

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

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

票数 6
EN

Stack Overflow用户

发布于 2016-11-09 05:13:00

只是另一种方式...

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

票数 1
EN

Stack Overflow用户

发布于 2016-11-09 04:51:57

如果你想循环遍历每个十六进制数字,那么只需从末尾循环到开头,在相加时将每个数字向左移动4位(每个十六进制数字的长度是4位):

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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40495841

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档