title: Convert a hexadecimal to a float and viceversa in C
body: <p>I'm trying to write an algorithm to convert a hexadecimal number to a floating point number and vice versa. This is part of an assignment, the program is supposed to receive either an 8 digit hexadecimal number that starts with '0x' or a floating point number, and using the computer's 'built in IEEE 754 capabilities' convert the number to hex or float. The code should be in C.</p>
  
  <p>My approach is the following. Store the input by the user as a string. Pass the input char array to a method that checks if it's a hexadecimal number by checking the first two positions of the array, which should be 0 and X (assume all hex numbers are passed this way). If this is the case, then I check that the hex is in the appropriate form, i.e not too many digits or numbers outside the 0-15 range (also considering the ABCDEF convention).</p>
  
  <p>So, my problem is, I don't know how to turn this array back into a number that I can use to convert to floating point. I thought about using sscanf to turn it back into a float but I don't know enough C and haven't found any good sources online</p>
  
  <p>Can somebody point me in the right direction? I also thought about storing the user input both as a string and a number at the same time, but I am not sure if this is possible.</p>
  
  <p>Here are the two form checking functions and the incomplete main method:</p>
  
  <pre><code>int is_hex(char arr[])
  {
      if (arr[0] == '0' &amp;&amp; (arr[1] == 'x' || arr[1] == 'X')) {
          return 1;
      }
      return 0;
  }
  
  int check_if_good(char arr[])
  {
      if (is_hex(arr)) {
          int len = strlen(arr);
          for (int i = 2; i &lt; len; i++) {
              if ((arr[i] &gt; 'f' &amp;&amp; arr[i] &lt;= 'z') || (arr[i] &gt; 'F' &amp;&amp; arr[i] &lt;= 'Z')) {
                  return 0;
              }
          }
      }
  
      return 1;
  }
  
  int main(int argc, const char * argv[])
  {
      float x;
      char input[30];
      scanf("%s", input);
      printf("%s", input);
      return 0;
  }
  </code></pre>
  
  <p>If somebody could also tell me the basics of what '%x' means i would really appreciate it. From what I understand it lets me collect numbers in hexadecimal form, but can i store them in ints and floats? Thank you very much for your help.</p>
  
  <p>--Edit: Extra code for floris. I'm trying to solve this problem without using any extra libraries, so you can't use the stdint lib. </p>
  
  <pre><code>char input[30];
  scanf("%s", input);
  if(check_if_good(input)){  //Ignore this if-statement.
      printf("Input is in hex form");
  }
  int num = convert_hex_string(input); // this function works perfectly. It return the int form of the hex.
  double f = *((double*)&amp;num);
  printf("%f\n", f);
  </code></pre>