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

    -

  • 相关阅读:
    POJ1270 Following Orders[拓扑排序所有方案 Kahn]
    拓扑排序 POJ2367Genealogical tree[topo-sort]
    如何使用MySQL Workbench创建数据库存储过程
    sql server数据库中 smallint, int ,bigint ,tinyint的区别与长度
    now() 的用法
    存储过程制造数据
    JMeter—系统性能分析思路
    JMeter—监听器
    JMeter—断言
    Jmeter后置处理器之JSON Extractor
  • 原文地址:https://www.cnblogs.com/fqh123/p/15415710.html
Copyright © 2011-2022 走看看