Skip to content

Instantly share code, notes, and snippets.

@kosmolot
Created July 8, 2017 10:39
Show Gist options
  • Save kosmolot/9240d7b5bc2376d060f6f59c4b09591d to your computer and use it in GitHub Desktop.
Save kosmolot/9240d7b5bc2376d060f6f59c4b09591d to your computer and use it in GitHub Desktop.
Half-precision floating-point. See https://stackoverflow.com/a/22283596
/**
* half-precision floating-point
*/
public struct Half {
public static int16 float_to_half (float single) {
int16 flt16;
int32 flt32 = 0;
Memory.copy(&flt32, &single, sizeof(float));
flt16 = (int16) (((flt32 & 0x7fffffff) >> 13) - (0x38000000 >> 13));
flt16 |= ((flt32 & 0x80000000) >> 16);
return flt16;
}
public static float half_to_float (int16 half) {
int32 flt32 = ((half & 0x8000) << 16);
flt32 |= ((half & 0x7fff) << 13) + 0x38000000;
float flt = 0;
Memory.copy(&flt, &flt32, sizeof(float));
return flt;
}
public int16 val { get; set; }
public Half (int16 half) {
_val = val;
}
public Half.from_float (float single) {
_val = float_to_half(single);
}
public float to_float () {
return half_to_float(_val);
}
public Half add (Half other) {
int16 half = float_to_half( to_float() + other.to_float() );
return *(Half*)(&half);
}
public Half sub (Half other) {
int16 half = float_to_half( to_float() - other.to_float() );
return *(Half*)(&half);
}
public Half mul (Half other) {
int16 half = float_to_half( to_float() * other.to_float() );
return *(Half*)(&half);
}
public Half div (Half other) {
int16 half = float_to_half( to_float() / other.to_float() );
return *(Half*)(&half);
}
/**
* Inverts the sign(+/-) of the number
*/
public Half invert () {
int16 half = float_to_half( -to_float() );
return *(Half*)(&half);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment