Last active
June 2, 2024 11:49
-
-
Save martandrMC/c2584eb18e34fb6cf252842f22ec6ae0 to your computer and use it in GitHub Desktop.
Software Integer to Float conversion (This was just an exercise to understand floats better, it is not recommended you use this)
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
uint8_t gen_exp(int32_t num) { | |
uint32_t mask = 1<<31; | |
uint8_t cnt = 31; | |
for(; cnt>0; cnt--) { | |
if(mask & num) break; | |
mask >>= 1; | |
} | |
return cnt; | |
} | |
float int_to_float(int32_t x) { | |
if(x == 0) return 0.0f; | |
uint32_t my_float = 0; | |
if(x < 0) my_float |= (1<<31), x = -x; | |
uint8_t exp = gen_exp(x); | |
my_float |= (exp+127) << 23; | |
if(exp > 23) { | |
x >>= exp - 24; | |
if(x&1) x++; | |
x >>= 1; | |
} else x <<= (23-exp); | |
my_float |= x & ((1<<23) - 1); | |
return *(float *) &my_float; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment