double to hex string & hex string to double

后端 未结 9 1449
南方客
南方客 2021-01-02 20:51

What I\'m trying to do is to convert a double to hex string and then back to double.

The following code does conversion double-to-hex string.

char *          


        
9条回答
  •  悲哀的现实
    2021-01-02 21:35

    I am surprised to see nobody has come up with the standard solution, which is the %a format specifier in the ISO C99 Standard.

    #include 
    #include 
    #include 
    
    std::string double2hexastr(double d) {
    
      char buffer[25] = { 0 };
    
      ::snprintf(buffer, 25, "%A", d); // TODO Check for errors
    
      return buffer;
    }
    
    double hexastr2double(const std::string& s) {
    
      double d = 0.0;
    
      ::sscanf(s.c_str(), "%lA", &d); // TODO Check for errors
    
      return d;
    }
    
    
    int main() {
    
      std::cout << "0.1 in hexadecimal: " << double2hexastr(0.1) << std::endl;
    
      std::cout << "Reading back 0X1.999999999999AP-4, it is ";
    
      std::cout << hexastr2double("0X1.999999999999AP-4") << std::endl;
    
    }
    

提交回复
热议问题