Converting double to char* in C++ with high performance

后端 未结 8 1535
野趣味
野趣味 2020-12-15 04:23

My application needs to convert double values to char* to write to a pipe that accepts only characters. The usual ways of doing this are using the sprintf() functio

相关标签:
8条回答
  • 2020-12-15 04:50
    /*
    
    _ecvt_s Converts a double number to a string.
    
    Syntax:
    
    errno_t _ecvt_s( 
       char * _Buffer,
       size_t _SizeInBytes,
       double _Value,
       int _Count,
       int *_Dec,
       int *_Sign
    );
    
    [out] _Buffer
    Filled with the pointer to the string of digits, the result of the conversion.
    
    [in] _SizeInBytes
    Size of the buffer in bytes.
    
    [in] _Value
    Number to be converted.
    
    [in] _Count
    Number of digits stored.
    
    [out] _Dec
    Stored decimal-point position.
    
    [out] _Sign
    Sign of the converted number.
    
    
    */
    
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    
    ...
    char *buf = (char*) malloc(_CVTBUFSIZE);
    int decimal;
    int sign;
    int err;
    
    
    err = _ecvt_s(buf, _CVTBUFSIZE, 1.2, 5, &decimal, &sign);
    
    if (err != 0) {
    // implement error handling
    }
    else printf("Converted value: %s\n", buf);
    
    ...
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-15 04:56

    Are you in control of both ends of the pipe? Are you just trying to tunnel doubles through or do you need a valid text representation of the double?

    If you are just tunneling and the pipe is 8 bit clean then use one of the answers above.

    If you need a string use one of the other answers above.

    If your problem is that the pipe is only 7 bits wide, then convert to radix 64 on write and back again on read.

    0 讨论(0)
提交回复
热议问题