Commits

Shu Zong Chen committed 5da48a3

special cases in double precision

  • Participants
  • Parent commits 8ce37fe

Comments (0)

Files changed (2)

 	POW5 = Math.pow(2, 5);
 	POW7 = Math.pow(2, 7);
 	POW8 = Math.pow(2, 8);
+	POW11 = Math.pow(2, 11);
 	POW16 = Math.pow(2, 16);
 	POW32 = Math.pow(2, 32);
 
 
 	struct.prototype.read_ulonglong = function(){
 		var hb = this.read_ulong();
-		var lb = this.read_long();
+		var lb = this.read_ulong();
 		return (hb * POW32) + lb;
 	};
 
 	struct.prototype.read_float = function(){
 		var ba = new bitarray(this.read_ulong(), 32);
 		var sign = ba.at(0);
-		var i = 0;
+		var i;
 		var exponent = 0;
 		for (i=0; i<8; i++){
 			exponent = (exponent * 2) + ba.at(i + 1);
 		}
 		if (exponent === 0){
-			return 0.0;
+			return 0;
 		}
 		var significand = 1;
 		for (i=1; i<24; i++){
 			significand += ba.at(i+8) * Math.pow(2, -i);
 		}
-		console.log(exponent);
 		if (exponent === POW8 - 1){
 			if (significand === 1){
 				return Math.pow(-1, sign) * Infinity;
 	struct.prototype.read_double = function(){
 		var ba = new bitarray(this.read_ulonglong(), 64);
 		var sign = ba.at(0);
-		var i = 0;
+		var i;
 		var exponent = 0;
 		for (i=0; i<11; i++){
 			exponent = (exponent * 2) + ba.at(i + 1);
 		console.log("sign: " + sign);
 		console.log("exponent: " + exponent);
 		console.log("significand: " + significand);
+		if (exponent === 0){
+			if (significand === 1){
+				return 0;
+			}
+			significand -= 1;
+		}
+		if (exponent === 2047){
+			if (significand === 1){
+				return Math.pow(-1, sign) * Infinity;
+			}
+			return NaN;
+		}
 		return Math.pow(-1, sign) * significand * Math.pow(2, exponent - 1023);
 	};
 

File test/unpack-test.js

 	["float 1", 1.0, [0xca, 0x3f, 0x80, 0x00, 0x00]],
 	["float -2", -2.0, [0xca, 0xc0, 0x00, 0x00, 0x0]],
 	["float 25", 25, [0xca, 0x41, 0xc8, 0x00, 0x0]],
+	["double 0", 0, [0xcb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]],
+	["double inf", Infinity, [0xcb, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]],
+	["double -inf", -Infinity, [0xcb, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]],
+	["double NaN", NaN, [0xcb, 0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]],
 	["double 1/3", 1/3, [0xcb, 0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55]],
 	["double 1", 1.0, [0xcb, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]],
 	["double 2", 2.0, [0xcb, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]],
 	var result = _result.join('');
 	if (isNaN(value)){
 		SimpleBatch[name] = function(topic){
+			console.log(name);
 			assert.strictEqual(isNaN(topic.unpack(result)), true);
 		};
 	} else {
 		SimpleBatch[name] = function(topic){
+			console.log(name);
 			assert.strictEqual(topic.unpack(result), value);
 		};
 }