Last active
October 15, 2020 09:44
-
-
Save faan11/247e2efe3ac5562d786053b4d543ed39 to your computer and use it in GitHub Desktop.
Half float to float and viceversa... No infinity No NaN managed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uint16_t convertFloatToHalf(float in) { | |
if (in == 0){ | |
return 0; | |
} | |
F32 f; | |
f.value = in; | |
F16 hf; | |
/** | |
* Use sign | |
*/ | |
hf.bit.sign = f.bit.sign; | |
hf.bit.exponent = f.bit.exponent - 112u; // (127u))+(15u)); | |
hf.bit.mantissa = (f.bit.mantissa >> 13u); | |
return hf.hfvalue; | |
} | |
float convertHalfToFloat(uint16_t in) { | |
if (in == 0 ){ | |
return in; | |
} | |
F32 f; | |
F16 hf; | |
hf.hfvalue = in; | |
/** | |
* Use sign | |
*/ | |
f.bit.sign = hf.bit.sign; | |
f.bit.exponent = hf.bit.exponent + 112u; // - (15u))+(127u); | |
f.bit.mantissa = (hf.bit.mantissa << 13u); | |
return f.value; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typedef union | |
{ | |
struct | |
{ | |
unsigned int mantissa:23; | |
unsigned int exponent:8; | |
unsigned int sign:1; | |
}bit; | |
uint32_t iv; | |
float value; | |
}F32; | |
typedef union | |
{ | |
struct | |
{ | |
unsigned int mantissa:10; | |
unsigned int exponent:5; | |
unsigned int sign:1; | |
unsigned int unused:16; | |
}bit; | |
float value; | |
uint16_t hfvalue; | |
}F16; | |
uint16_t convertFloatToHalf(float in); | |
float convertHalfToFloat(uint16_t in); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment