Skip to content

Instantly share code, notes, and snippets.

@cabo
Created April 15, 2013 14:59
Show Gist options
  • Save cabo/5388730 to your computer and use it in GitHub Desktop.
Save cabo/5388730 to your computer and use it in GitHub Desktop.
Convert an IEEE 754 Half-precision (16-bit) float into a native float in 11 instructions and 1 branch. Portable to IEEE 754 Single-precision implementations (i.e., everything post-VAX).
float decode_half(int half) {
union { uint32_t u; float f; } val;
val.u = (half & 0x7fff) << 13 | (half & 0x8000) << 16;
if ((half & 0x7c00) != 0x7c00)
return val.f * 0x1p112;
val.u |= 0x7f800000;
return val.f;
}
@matthiesenj
Copy link

please note that this doesn't work on platforms where sizeof(int) < 4, because the shifts will overflow.
also, it involves a floating point multiplication, so may not be the optimal for platforms without fpu.

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