Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a haxe.Int64 to a Float?

Tags:

haxe

How can I convert a haxe.Int64 to a Float?

I've got something like

var x = haxe.Int64.parseString("1000000000000");

and I'd like to convert that to a Float. I've looked in the Int64 api docs, have found fromFloat, ofInt, and toInt, but there's no toFloat method in there.

like image 363
uvtc Avatar asked Oct 22 '25 12:10

uvtc


2 Answers

I cannot see that functionality in the Haxe standard library either, I checked Int64 and Int64Helper.

However the MIT-licensed thx.core library does include an implementation, see below: https://github.com/fponticelli/thx.core/blob/master/src/thx/Int64s.hx#L137

using haxe.Int64;

class Int64s {

  static var zero = Int64.make(0, 0);
  static var one = Int64.make(0, 1);
  static var min = Int64.make(0x80000000, 0);

/**
Converts an `Int64` to `Float`;
Implementation by Elliott Stoneham.
*/
  public static function toFloat(i : Int64) : Float {
    var isNegative = false;
    if(i < 0) {
      if(i < min)
        return -9223372036854775808.0; // most -ve value can't be made +ve
      isNegative = true;
      i = -i;
    }
    var multiplier = 1.0,
        ret = 0.0;
    for(_ in 0...64) {
      if(i.and(one) != zero)
        ret += multiplier;
      multiplier *= 2.0;
      i = i.shr(1);
    }
    return (isNegative ? -1 : 1) * ret;
  }
}

Using the library method worked for me, tested on the JavaScript target like so:

import haxe.Int64;
import thx.Int64s;

class Main {    
    public static function main():Void {
        var x:Int64 = haxe.Int64.parseString("1000000000000");
        var f:Float = thx.Int64s.toFloat(x);
        trace(f); // Prints 1000000000000 to console (on js target)
    }
}
like image 124
Sam Twidale Avatar answered Oct 26 '25 10:10

Sam Twidale


Alternatively, you can convert Int64 to Float yourself by combining high/low halves:

class Test {
  static function main() {
    var x = haxe.Int64.parseString("1000000000000");
    var f = x.high * 4294967296. + (x.low >>> 0);
    trace("" + x);
    trace(f);
  }
}

Here, 4294967296. is a float literal for unsigned 2^32;
>>> 0 is required because the lower half can be signed.

like image 23
YellowAfterlife Avatar answered Oct 26 '25 09:10

YellowAfterlife



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!