Skip to content
Snippets Groups Projects
Select Git revision
  • 0dc1fd416a6775a35501b71c565c957d60085a37
  • master default protected
2 results

test.html

Blame
  • fixmath.h 1.85 KiB
    #pragma once
    
    #include <stdint>
    
    
    // standard, even type (16.16) with range [-32768, 32768)
    typedef struct {
        uint32_t raw;
    } fix_t;
    
    // unit type (1.31) with range [-1, 1)
    typedef struct {
        uint32_t raw;
    } fix_unit_t;
    
    // fix_t functions
    static inline fix_t fix_eadd(fix_t x, fix_t y) {
        return (fix_t) { .raw = x.raw + y.raw };
    }
    
    static inline fix_t fix_esub(fix_t x, fix_t y) {
        return (fix_t) { .raw = x.raw - y.raw };
    }
    
    static inline fix_t fix_eneg(fix_t x) {
        return (fix_t) { .raw = -x.raw };
    }
    
    fix_t fix_emul(fix_t x, fix_t y);
    fix_t fix_ediv(fix_t x, fix_t y);
    
    fix_t fix_esqrt(fix_t x);
    
    static inline fix_t fix_efrom_int(int x) {
        return (fix_t) { .raw = x << 16 }
    }
    void fix_eto_string(fix_t x, char[] buf);
    
    // fix_unit_t functions
    static inline fix_unit_t fix_uadd(fix_unit_t x, fix_unit_t y) {
        return (fix_unit_t) { .raw = x.raw + y.raw };
    }
    
    static inline fix_unit_t fix_usub(fix_unit_t x, fix_unit_t y) {
        return (fix_unit_t) { .raw = x.raw - y.raw };
    }
    
    static inline fix_unit_t fix_eneg(fix_t x) {
        return (fix_unit_t) { .raw = -x.raw };
    }
    
    fix_unit_t fix_umul(fix_unit_t x, fix_unit_t y);
    fix_unit_t fix_udiv(fix_unit_t x, fix_unit_t y);
    
    fix_unit_t fix_usqrt(fix_unit_t x);
    
    static inline fix_unit_t fix_ufrom_reciprocal(int x) {
        return (fix_unit_t) { .raw = (1 << 31) / x };
    }
    
    void fix_uto_string(fix_t x, char[] buf);
    
    // generic macros
    # define fix_add(x, y) _Generic(x, fix_t: fix_eadd, fix_unit_t: fix_uadd)(x, y)
    # define fix_sub(x, y) _Generic(x, fix_t: fix_esub, fix_unit_t: fix_usub)(x, y)
    # define fix_mul(x, y) _Generic(x, fix_t: fix_emul, fix_unit_t: fix_umul)(x, y)
    # define fix_div(x, y) _Generic(x, fix_t: fix_ediv, fix_unit_t: fix_udiv)(x, y)
    
    # define fix_sqrt(x) _Generic(x, fix_t: fix_esqrt, fix_unit_t: fix_usqrt)(x)
    
    # define fix_to_string(x, buf) _Generic(x, fix_t: fix_eto_string, fix_unit_t: fix_uto_string)(x, buf)