Skip to content

Instantly share code, notes, and snippets.

@kbinani
Last active August 29, 2015 14:21
Show Gist options
  • Save kbinani/3e30454869b2c513380c to your computer and use it in GitHub Desktop.
Save kbinani/3e30454869b2c513380c to your computer and use it in GitHub Desktop.
Unpack IEEE754 binary32, from "int[4]" to "float"
float unpackIEEE754Binary32(int bytes[4]) {
/**
bytes[0][0]: sign {1 if minus}
bytes[0][1:7]: exponent(0:6)
bytes[1][0]: exponent(7)
bytes[1][1:7]: fraction(0:6)
bytes[2][0:7]: fraction(7:14)
bytes[3][0:7]: fraction(15:22)
*/
bool minus = false;
int exponent = 0;
if (bytes[0] >= 128) {
minus = true;
exponent = (bytes[0] - 128) * 2;
} else {
exponent = bytes[0] * 2;
}
if (bytes[1] >= 127) {
exponent += 1;
bytes[1] -= 128;
}
exponent -= 127;
float fraction = 1.0;
float base = 0.5;
int byteIndex = 1;
int bitIndex = 1;
int pow2 = 64; // pow2 = pow(2, 7 - bitIndex)
for (; byteIndex < 4; ++byteIndex) {
int b = bytes[byteIndex];
for (; bitIndex < 8; ++bitIndex) {
if (b >= pow2) {
fraction += base;
b -= pow2;
}
base *= 0.5;
pow2 /= 2;
}
bitIndex = 0;
pow2 = 128;
}
float v = fraction * pow(2.0, float(exponent));
if (minus) {
v *= -1.0;
}
return v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment