7134956

Untitled

Nov 22nd, 2019
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.90 KB | None | 0 0
  1. const char * const prefix = "yzafpnum KMGTPEZY";
  2. const float prefix_xf[] = {
  3. 1e-24, 1e-21, 1e-18, 1e-15, 1e-12, 1e-9, 1e-6, 1e-3,
  4. 1e+1,
  5. 1e+3, 1e+6, 1e+9, 1e+12, 1e+15, 1e+18, 1e+21, 1e+24};
  6.  
  7. float hum_to_float(const char *s) {
  8.     // This function stolen from either Rolf Neugebauer or Andrew Tolmach.
  9.     // Probably Rolf.
  10.     float a = 0.0f;
  11.     int e = 0;
  12.     int c;
  13.     float sign = 1;
  14.    
  15.     c = *s++;
  16.  
  17.     if(c == '-') {
  18.         sign = -1;
  19.         c = *s++;
  20.     }
  21.  
  22.     while(c != '\0' && isdigit(c)) {
  23.         a = a * 10.0f + (c - '0');
  24.         c = *s++;
  25.     }
  26.  
  27.     if(c == '.') {
  28.         while((c = *s++) != '\0' && isdigit(c)) {
  29.             a = a * 10.0f + (c - '0');
  30.             e = e - 1;
  31.         }
  32.     }
  33.  
  34.     if(c <= 'z' && c >= 'E') {
  35.         for(int i = 0; prefix[i] != '\0'; i++) {
  36.             if(c == prefix[i]){
  37.                 a *= prefix_xf[i];
  38.                 break;
  39.             }  
  40.         }
  41.     }
  42.    
  43.     while(e > 0) {
  44.         a *= 10.0f;
  45.         e--;
  46.     }
  47.  
  48.     while(e < 0) {
  49.         a *= 0.1f;
  50.         e++;
  51.     }
  52.  
  53.     return a * sign;
  54. }
Add Comment
Please, Sign In to add comment