【问题标题】:Read binary C float in Actionscript 3?在 Actionscript 3 中读取二进制 C 浮点数?
【发布时间】:2025-12-15 01:20:03
【问题描述】:

我有二进制 C/C++ 数据类型(例如,在 C 浮点数的内存版本中),我需要将其读入 Actionscript 3,并且不希望从头开始编写代码。

有人知道任何库、示例代码、伪代码来帮助解决这个问题吗?

例如:

C/C++ 应用程序:

float f = 1.1;
SaveFloatToFile(f, 'myfile.bin');

Actionscript 3 应用程序:

var ba:ByteArray = ReadFromFile('myfile.bin');
var f:Float = ParseFloat(ba); // I need code for ParseFloat() 

【问题讨论】:

    标签: c++ actionscript-3 file-io floating-point binary-data


    【解决方案1】:

    AS3 Number 类符合IEEE 754,与Javascript number 类相同。

    我没有搜索 AS3 库,而是四处寻找一些 Javascript 代码,这些代码只需在 AS3 中进行少量修改即可工作。

    this site 我发现了这个相当高密度的浮点解析器:

    p.decodeFloat = function( data, precisionBits, exponentBits ){
        var b = new this.Buffer( this.bigEndian, data );
        b.checkBuffer( precisionBits + exponentBits + 1 );
        var bias = Math.pow( 2, exponentBits - 1 ) - 1, signal = b.readBits( precisionBits + exponentBits, 1 ), exponent = b.readBits( precisionBits, exponentBits ), significand = 0,
        divisor = 2, curByte = b.buffer.length + ( -precisionBits >> 3 ) - 1;
        do
            for( var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 );
        while( precisionBits -= startBit );
        return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 );
    };
    

    如果您希望您的代码既可调试又可运行,您可能会发现this code 更有帮助。

    【讨论】:

      【解决方案2】:

      我做了更多的挖掘工作,发现 ByteArray 拥有我需要的大部分内容(可能事先进行了一些位移)

      【讨论】: