zoukankan      html  css  js  c++  java
  • 十进制与二进制的互相转换

    -

    // 将十进制转换为二进制
    function to2(number){
        return Number(number.toString(2));
    }
    console.log(to2(3));// 11
    
    
    /**
    * 将二进制小数部分转换为十进制数
    * @param binaryFloatPartArr 二进制小数部分中由小数各位组成的数组
    */
    function eachBinaryFloatPartToDecimal(binaryFloatPartArr) {
        return binaryFloatPartArr.map((currentValue, index) => {
            return Number(currentValue) * Math.pow(2, (-(index + 1)))
        })
    }
    
    /**
    * 将二进制小数(包含整数部分和小数部分)转换为十进制数
    * @param binaryNum 二进制数(可能是整数,也可能是小数)
    */
    function binaryFloatToDecimal(binaryNum) {
        // 如果该二进制只有整数部分则直接用 parseInt(string, radix) 处理
        if (Number.isInteger(binaryNum)) {
            return parseInt(binaryNum, 2)
        } else {
            const binaryFloatNumArr = binaryNum.toString().split(".")
    
            // 将二进制整数转换为十进制数
            const binaryIntParStr = binaryFloatNumArr[0]
            const decimalIntPartNum = parseInt(binaryIntParStr, 2)
    
            // 将二进制小数部分转换为十进制数
            const binaryFloatPartArr = binaryFloatNumArr[1].split("")
            const eachDecimalFloatPartNum = eachBinaryFloatPartToDecimal(binaryFloatPartArr)
            const deciamlFloatPartNum = eachDecimalFloatPartNum.reduce((accumulator, currentValue) => { return accumulator + currentValue })
            return decimalIntPartNum + deciamlFloatPartNum
        }
    }
    
    console.log(binaryFloatToDecimal(1111011.111))  // 123.875
    console.log(binaryFloatToDecimal(1111011))  // 123
    console.log(binaryFloatToDecimal(0.111))  // 0.875
    console.log(to2(123.875));// 1111011.111
    console.log(to2(123));// 1111011
    console.log(to2(0.875));// 0.111

    -

  • 相关阅读:
    WinForm中AssemblyInfo.cs文件参数具体讲解
    ISO18000-6B和ISO18000-6C(EPC C1G2)标准的区别
    Win8.1下VM与Hyper-v冲突解决方法
    Mifare l卡特性简介
    【Python爬虫】beautifulsoup4库的安装与调用
    【Python爬虫】已知jpg文件url-下载图片
    【Python爬虫】测试
    【Python爬虫】Requests库的安装
    【Python】以模块化做比赛模拟
    【真随笔】未来出路,在哪里?
  • 原文地址:https://www.cnblogs.com/fqh123/p/15415710.html
Copyright © 2011-2022 走看看