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

    -

  • 相关阅读:
    Python-爬取小说内容并下载
    Python-网易音乐下载
    [Python图像处理]六.图像缩放,图像旋转,图像翻转与图像平移
    [Python图像处理]五.图像加法运算,图像融合及图像类型转换
    [Python图像处理]四.图像平滑中四种常用的滤波
    go语言-从控制套获取用户输入
    go语言-运算符
    go语言-指针
    go语言-数据类型及类型之间转换
    go语言-变量与常量
  • 原文地址:https://www.cnblogs.com/fqh123/p/15415710.html
Copyright © 2011-2022 走看看