Question

I was wondering if there an established convention to specifying fixed point binary numbers in decimal format (with the use of a macro). I am not sure if this possible in C/C++, but perhaps this is implemented in some language(s) and there is a notational standard like 0x000000,1.2f,1.2d,1l,etc

Take this example for instance:

I am using Q15.16 for instance, but would like to have the convenience of specifying numbers in decimal format, perhaps something like this:

var num:Int32=1.2fp;

Presumably, the easiest way with regards to Haxe macros, numbers can be initialized with a function:

@:macro fp_from_float(1.2);

But it would be nice to have a shorthand notation.

Était-ce utile?

La solution

Have you seen Luca's Fixed Point example with Haxe 3 and Abstracts? It's here: https://groups.google.com/forum/?fromgroups=#!topic/haxelang/JsiWvl-c0v4

Summing it up, with the new Haxe 3 abstract types, you can define a type that will be compiled as an Int:

abstract Fixed16(Int) 
{
    inline function new(x:Int) this = x;
}

You can also define "conversion functions", which will allow you to automatically convert a float into Fixed16:

@:from public static inline function fromf(x:Float) {
    #if debug
        if (x >= 32768.0 || x < -32768.0) throw "Conversion to Fixed16 will overflow";
    #end
    return new Fixed16(Std.int(x*65536.0));
}

The secret here is the @:from metadata. With this code, you will already be able to declare fixed types like this:

var x:Fixed16 = 1.2;

Luca's already defined some operators, to make working with them easier, like:

 @:op(A+B) public inline static function add(f:Fixed16, g:Fixed16) {
        #if debug
            var fr:Float = f.raw();
            var gr:Float = g.raw();
            if (fr+gr >= 2147483648.0 || fr+gr < -2147483648.0) throw "Addition of Fixed16 values will overflow";
        #end
        return new Fixed16(f.raw()+g.raw());
    }

Again, the secret here is in @:op(A+B) metadata, which will annotate that this function may be called when handling addition. The complete GIST code is available at https://gist.github.com/deltaluca/5413225 , and you can learn more about abstracts at http://haxe.org/manual/abstracts

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top