如何将二进制分数转换为十进制 [英] How to convert binary fraction to decimal

查看:130
本文介绍了如何将二进制分数转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript具有函数parseInt(),该函数可以帮助将二进制形式的整数转换为等效的十进制数:

Javascript has the function parseInt() which can help convert integer in a binary form into its decimal equivalent:

parseInt("101", 2) // 5

但是,我需要将二进制分数转换为它的十进制等效值,例如:

However, I need to convert binary fraction to its decimal equivalent, like:

0.101 = 0.625

我可以编写自己的函数来计算结果,如下所示:

I can write my own function that would calculate the result like the following:

1 * Math.pow(2, -1) + 0*Math.pow(2, -2) + 1*Math.pow(2, -3) // 0.625

但是我想知道是否已经有任何标准.

But I'm wondering whether there is anything standard already.

推荐答案

您可以在点处拆分数字(作为字符串),并使用自己的函数处理整数部分,并使用另一个函数处理小数部分以获取正确的值.

You can split the number (as string) at the dot and treat the integer part with an own function and the fraction part with another function for the right value.

该解决方案也可以与其他基地一起使用.

The solution works with other bases as well.

function convert(value, base = 2) {
    var [integer, fraction = ''] = value.toString().split('.');

    return parseInt(integer, base) + (integer[0] !== '-' || -1) * fraction
        .split('')
        .reduceRight((r, a) => (r + parseInt(a, base)) / base, 0);
}

console.log(convert(1100));           //    12
console.log(convert(0.0011));         //     0.1875
console.log(convert(1100.0011));      //    12.1875

console.log(convert('ABC', 16));      //  2748
console.log(convert('0.DEF', 16));    //     0.870849609375
console.log(convert('ABC.DEF', 16));  //  2748.870849609375

console.log(convert('-ABC.DEF', 16)); // -2748.870849609375
console.log(convert(-1100.0011));     //   -12.1875

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于如何将二进制分数转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆