views:

487

answers:

2

I have binary C/C++ data types (e.g. in memory version of a C float) which I need to read into Actionscript 3 and would prefer not to code this from scratch.

Anyone know of any libraries, sample code, pseudo code to help with this?

For example:

C/C++ app:

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

Actionscript 3 app:

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

The AS3 Number class conforms to IEEE 754, and is identical to the Javascript number class.

Rather than search for AS3 libraries, I dug around for some Javascript code that should work with only minor modification in AS3.

On this site I found this rather high-density float parser:

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 );
};

If you prefer your code to be debuggable as well as functional, you may find this code to be more helpful instead.

HanClinto
A: 

I did some more digging around and discovered that ByteArray has most of what I need (possibly with some bit shifting beforehand)

Brian