Browse Source

added Output.writeFloat and Input.readFloat

Simon Krajewski 13 years ago
parent
commit
0f8be3d8d1
3 changed files with 37 additions and 8 deletions
  1. 14 3
      std/haxe/io/Input.hx
  2. 20 2
      std/haxe/io/Output.hx
  3. 3 3
      tests/unit/TestIO.hx

+ 14 - 3
std/haxe/io/Input.hx

@@ -147,8 +147,19 @@ class Input {
 			var a = untyped __call__('unpack', 'f', readString(4));
 			return a[1];
 		#else
-			throw "Not implemented";
-			return 0;
+			var bytes = [];
+			bytes.push(readByte());
+			bytes.push(readByte());
+			bytes.push(readByte());
+			bytes.push(readByte());
+			if (bigEndian)
+				bytes.reverse();
+			var sign = 1 - ((bytes[0] >> 7) << 1);
+			var exp = (((bytes[0] << 1) & 0xFF) | (bytes[1] >> 7)) - 127;
+			var sig = ((bytes[1] & 0x7F) << 16) | (bytes[2] << 8) | bytes[3];
+			if (sig == 0 && exp == -127)
+				return 0.0;
+			return sign*(1 + Math.pow(2, -23)*sig)*Math.pow(2, exp);
 		#end
 	}
 
@@ -162,7 +173,7 @@ class Input {
 			return a[1];
 		#else
 			throw "Not implemented";
-			return 0;
+			return 0.0;
 		#end
 	}
 

+ 20 - 2
std/haxe/io/Output.hx

@@ -31,7 +31,7 @@ package haxe.io;
 	Output.
 **/
 class Output {
-
+	private static var LN2 = Math.log(2);
 	public var bigEndian(default,setEndian) : Bool;
 
 	public function writeByte( c : Int ) : Void {
@@ -101,7 +101,25 @@ class Output {
 		#elseif php
 		write(untyped Bytes.ofString(__call__('pack', 'f', x)));
 		#else
-		throw "Not implemented";
+		if (x == 0.0)
+		{
+			writeByte(0); writeByte(0);	writeByte(0); writeByte(0);
+			return;
+		}
+		var exp = Math.floor(Math.log(Math.abs(x)) / LN2);
+		var sig = (Math.floor(Math.abs(x) / Math.pow(2, exp) * (2 << 22)) & 0x7FFFFF);
+		var b1 = (exp + 0x7F) >> 1 | (exp>0 ? ((x<0) ? 1<<7 : 1<<6) : ((x<0) ? 1<<7 : 0)),
+			b2 = (exp + 0x7F) << 7 & 0xFF | (sig >> 16 & 0x7F),
+			b3 = (sig >> 8) & 0xFF,
+			b4 = sig & 0xFF;
+		if (bigEndian)
+		{
+			writeByte(b4); writeByte(b3); writeByte(b2); writeByte(b1);
+		}
+		else
+		{
+			writeByte(b1); writeByte(b2); writeByte(b3); writeByte(b4);
+		}
 		#end
 	}
 

+ 3 - 3
tests/unit/TestIO.hx

@@ -45,8 +45,8 @@ class TestIO extends Test {
 		o.writeByte(98);
 		#if (neko || flash9 || php || cpp)
 		o.writeDouble(1.23);
-		o.writeFloat(1.2e10);
 		#end
+		o.writeFloat(1.2e10);
 		o.writeByte(99);
 
 		var str = "Héllo World !";
@@ -93,12 +93,12 @@ class TestIO extends Test {
 		eq( i.readByte(), 98 );
 		#if (neko || flash9 || php || cpp)
 		eq( i.readDouble(), 1.23 );
-		eq( i.readFloat(), 1.2e10 );
 		#else
 		// these two are not implemented
 		exc(function() i.readDouble());
-		exc(function() i.readFloat());
+		//exc(function() i.readFloat());
 		#end
+		eq( i.readFloat(), 1.2e10 );
 		eq( i.readByte(), 99 );
 
 		eq( i.readString(haxe.io.Bytes.ofString(str).length), str );