Created
April 23, 2018 23:15
-
-
Save bit-hack/4e79cbb766daf959b683ea734dc3f799 to your computer and use it in GitHub Desktop.
float to fixed point 16:16
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
#include <cstdint> | |
#include <cstring> | |
// float to int | |
int32_t float_to_int(float myfloat) { | |
uint32_t fint = 0; | |
memcpy(&fint, (void*)&myfloat, 4); | |
constexpr uint32_t mask_fract = (1u << 23) - 1; | |
const uint32_t fract = (fint & mask_fract) | (1u << 23); | |
const uint32_t fexpn = (fint >> 23) & 0xff; | |
const uint32_t fsign = (fint >> 31) & 1u; | |
const int32_t t = fract << ((fexpn - 127) - 23); | |
return fsign ? ~t + 1 : t; | |
} | |
// float to 16:16 fixed point | |
int32_t float_to_fixed(float myfloat) { | |
uint32_t fint = 0; | |
memcpy(&fint, (void*)&myfloat, 4); | |
constexpr uint32_t mask_fract = (1u << 23) - 1; | |
const uint32_t fract = (fint & mask_fract) | (1u << 23); | |
const uint32_t fexpn = (fint >> 23) & 0xff; | |
const uint32_t fsign = (fint >> 31) & 1u; | |
const int32_t t = fract << ((fexpn - 127) - 7); | |
return fsign ? ~t + (1 << 16) : t; | |
} | |
int main() { | |
return float_to_fixed(-124.0f) >> 16; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment