Skip to content

Instantly share code, notes, and snippets.

@martinwells
Created April 2, 2014 22:23
Show Gist options
  • Save martinwells/9944457 to your computer and use it in GitHub Desktop.
Save martinwells/9944457 to your computer and use it in GitHub Desktop.
Convert an int64 to a float and back
import haxe.Int64;
class Int64Utils
{
private inline static var MAX_32_PRECISION = 4294967296;
public static function fromFloat(f:Float):Int64 {
return Int64.make(Std.int(f/MAX_32_PRECISION), Std.int(f-(f/MAX_32_PRECISION)));
}
public static function toFloat(i:Int64):Float {
return (Int64.getHigh(i) * MAX_32_PRECISION + Int64.getLow(i));
}
}
@hiepth
Copy link

hiepth commented Nov 18, 2014

I've corrected code as following:

private inline static var MAX_32_PRECISION:Float = 4294967296.0;

public static function fromFloat(f:Float):Int64
{
    var h = Std.int(f / MAX_32_PRECISION);
    var l = Std.int(f);
    return Int64.make(h, l);
}

public static function toFloat(i:Int64):Float
{
    var f:Float = Int64.getLow(i);
    if (f < 0) f += MAX_32_PRECISION;
    return (Int64.getHigh(i) * MAX_32_PRECISION + f);
}

@georgkoester
Copy link

Sadly this doesn't work:

  private inline static var MAX_32_PRECISION:Float = 4294967296.0;
public static function fromFloat(f:Float):Int64
{
var h = Std.int(f / MAX_32_PRECISION);
var l = Std.int(f);
return Int64.make(h, l);
}

trace(fromFloat(Std.parseFloat("5000000000"))); // yields 6442450944 on neko

@georgkoester
Copy link

See HaxeFoundation/haxe#3655 for a fromFloat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment