Last active
August 18, 2021 21:20
-
-
Save riicchhaarrd/4aaa44c8109fcada3ff735eae8a8ba69 to your computer and use it in GitHub Desktop.
convert integer to single float IEEE 754
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 <stdio.h> | |
| #include <stdlib.h> | |
| int to_float( int number ) | |
| { | |
| int flt = 0; | |
| if ( number < 0 ) | |
| { | |
| number = -number; | |
| flt |= ( 1 << 31 ); | |
| } | |
| int lz = 0; | |
| for ( int i = 0; i < 32; ++i ) | |
| { | |
| if ( number & ( 1 << ( 32 - i - 1 ) ) ) | |
| break; | |
| ++lz; | |
| } | |
| int exp = 32 - lz - 1; | |
| for ( int i = 0; i < lz; ++i ) | |
| { | |
| int bit = ( number & ( 1 << ( 32 - i - lz - 1 ) ) ) == 0 ? 0 : 1; | |
| flt |= ( bit << ( 32 - i - 1 - 8 ) ); | |
| } | |
| flt &= ~( 1 << 23 ); // clear leading 1 | |
| flt |= ( ( ( exp + 127 ) & 0xff ) << 23 ); | |
| return flt; | |
| } | |
| int main( int argc, char** argv ) | |
| { | |
| int n = atoi( argv[1] ); | |
| int f = to_float( n ); | |
| printf( "n = %d, as_float = %d, %f\n", n, f, *(float*)&f ); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment