views:

548

answers:

1

Is it possible to get the raw bytes of a floating point (IEEE-754) Number object in Actionscript?

Or alternately, if I can get the sign (1 bit), mantissa (52 bits) and exponent (11 bits), then I can do the bitshifting myself and construct the raw byte array.

I'd like to create precise, compact string representations of Number values (hex, base-36, base-64, etc) for certain serialization situations.

I may also be interested in constructing compact 16-bit floats (IEEE half precision) and packing them into dense byte arrays.

For example, in Java, I might write code like this to create precise string representations of doubles:

public static String hexRepresentation(double value) {
   long bits = Double.doubleToLongBits(value);
   String hex = Long.toHexString(bits);
   return hex;
}

public static String b36Representation(double value) {
   long bits = Double.doubleToLongBits(value);
   String hex = Long.toString(bits, 36);
   return hex;
}

public static void main(String[] args) {
   System.out.println(hexRepresentation(123.456)); // 405edd2f1a9fbe77
   System.out.println(hexRepresentation(Math.PI)); // 400921fb54442d18

   System.out.println();

   System.out.println(b36Representation(123.456)); // z8nf9qi2e5pz
   System.out.println(b36Representation(Math.PI)); // z21th0e6pjiw
}

If anyone has any ideas for how to accomplish the same thing in actionscript, I'd love to know. But so far, it doesn't seem possible. What about those new opcodes in the FP10 for Alchemy? Is there anything there that lets you get at the raw bytes somehow?

+1  A: 

I'm pretty sure you could do this just by creating a bytearray and then calling writeFloat on it. You could then read off each byte with readByte then shift and mask as needed to get exactly what you want.

Branden Hall
Ah. Of course! That's just like casting a float pointer to an int pointer in C. Very nice.
benjismith