【问题标题】:convert 9.2532 decimal into binary matlab将 9.2532 十进制转换为二进制 matlab
【发布时间】:2017-08-07 04:33:35
【问题描述】:

我使用 de2bi(x),但它仅对整数有帮助,我想将带小数点的数字转换为二进制

de2bi(x)

如果可能的话,将这个 9.2553 转换为带有小数部分的十进制,也可以在 Matlab 中转换为二进制格式,而不是没有带有代码的函数文件想要输出

【问题讨论】:

    标签: xcode matlab binary


    【解决方案1】:

    当然,MATLAB 已经使用IEEE-754 binary64 格式以二进制形式存储双精度值。我们所要做的就是让 MATLAB 向我们展示这些位。

    一种方法是使用typecast,它使 MATLAB 将一组内存位置解释为不同的类型。在这种情况下,我们会让 MATLAB 认为 doubleuint64,然后通过 dec2bin 发送“整数”。之后我们必须对字符串进行一些分解以获得实际值。

    注意:这目前仅适用于正值。如果您也需要负值,我将不得不进行一些调整。

    function binstr = double2bin(d)
       d = double(d);   % make sure the input is a double-precision float
       ieee754_d = dec2bin(typecast(d, 'uint64'),64);   % read double as uint64
       % IEEE-754 64-bit double:
       %    bit 1 (msb) = sign bit (we'll ignore this for now)
       %    bits 2-12   = exponent with bias of 1023
       %    bits 13-64  = significand with leading 1 removed (implicit)
       exponent = bin2dec(ieee754_d(2:12))-1022;   % 2^n has n+1 bits
       significand = ['1' ieee754_d(13:64)];
       if (exponent < 1)   % d < 1, so we'll need to pad with zeros
          binstr = ['0.' repmat('0',1,-exponent) significand];
       else   % d >= 1; move exponent bits to the left of binary point
          binstr = [significand(1:exponent) '.' significand(exponent+1:end)];
       end
    end
    

    试运行:

    >> double2bin(9.2532)
    ans = 1001.0100000011010001101101110001011101011000111000100
    

    【讨论】:

      【解决方案2】:

      临时解决方案:

      2^44 扩展(以获得整数值)。
      将整数结果转换为二进制。
      通过放置“小数”点减少2^44
      2^44 是给出整数结果的 2 扩展的最小幂)。

      代码示例:

      expandedRes = dec2bin(9.2553*2^44);
      res = expandedRes[1:end-44, '.', end-43:end);
      

      结果:

      res =
      
      1001.01000001010110110101011100111110101010110011
      

      【讨论】:

        猜你喜欢
        • 2016-03-16
        • 2012-06-26
        • 1970-01-01
        • 2015-10-27
        • 1970-01-01
        • 2013-01-24
        • 2016-08-28
        相关资源
        最近更新 更多