Created
April 10, 2013 10:53
-
-
Save masbog/5353635 to your computer and use it in GitHub Desktop.
How To Create Hex or Binary Value from Float Point
how ho use :
compile first using 'g++ float2hex.cpp' and then rename a.out to float2hex
last copy float2hex into /usr/local/bin result :
Macintosh:masbog$ float2hex 2.34
Your Float value is : 2.340000
Result Float to Hex is : 0x4015C28F
Your binary value is : 0100 0000 0001 0101 0010 1000
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 <bitset> | |
| #include <string> | |
| #include <iostream> | |
| #include <sstream> | |
| using namespace std; | |
| int main(int argc, char **argv) | |
| { | |
| if(int(argc) > 1) | |
| { | |
| float a = atof(argv[1]); | |
| printf("Your Float value is : %f\nResult Float to Hex is : 0x%X\n", a, *(int *)&a); | |
| char buffer[8]; | |
| int n; | |
| n = sprintf(buffer, "%X", *(int *)&a); | |
| std::string sReturn; | |
| for (int i = 0; i < n; ++i) | |
| { | |
| switch (buffer [i]) | |
| { | |
| case '0': sReturn.append ("0000 "); break; | |
| case '1': sReturn.append ("0001 "); break; | |
| case '2': sReturn.append ("0010 "); break; | |
| case '3': sReturn.append ("0011 "); break; | |
| case '4': sReturn.append ("0100 "); break; | |
| case '5': sReturn.append ("0101 "); break; | |
| case '6': sReturn.append ("0110 "); break; | |
| case '7': sReturn.append ("0111 "); break; | |
| case '8': sReturn.append ("1000 "); break; | |
| case '9': sReturn.append ("1001 "); break; | |
| case 'a': sReturn.append ("1010 "); break; | |
| case 'b': sReturn.append ("1011 "); break; | |
| case 'c': sReturn.append ("1100 "); break; | |
| case 'd': sReturn.append ("1101 "); break; | |
| case 'e': sReturn.append ("1110 "); break; | |
| case 'f': sReturn.append ("1111 "); break; | |
| } | |
| } | |
| printf("Your binary value is : %s\n", sReturn.c_str()); | |
| }else | |
| { | |
| printf("Please use example like this : \"float2hex 2.34\"\n"); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment