0

I am trying to convert a "double" value (say 1.12345) to 8 byte hex string. I am using the following function to convert double value to hex string.

std::string double_to_hex_string(double d)
{
unsigned char *buffer = (unsigned char*)&d;
const int bufferSize = sizeof(double);

char converted[bufferSize * 2 + 1];
//char converted[bufferSize];

int j = 0;
for(int i = 0 ; i < bufferSize ; ++i)
{
    sprintf(&converted[j*2], "%02X", buffer[i]);
    ++j;
}
string hex_string(converted);
return hex_string;
}

This function returns the 16 byte hex string. I then compress this string to fit into 8 bytes through this code

string hexStr = double_to_hex_string(TempD);

unsigned char sample[8];

for ( int i = 0; i < hexStr.length() / 2 ; i++) 
{
sscanf( (hexStr.substr(i*2,2)).c_str(), "%02X", &sample[i]);
}

Now, how can I get the hex digits representing these 8 bytes in "sample" array. There should be only one hex digit per byte. I need to append this 8 byte hex string to a global string.

If there is any other solution which can convert a double value to 8 hex digits and vice versa, that would be highly appreciated.

Regards.

4

1 回答 1

1

A hexidecimal digit represents half a byte, so if you are limited to 8 hex digits you are also limited to storing 4 bytes.

This solution will encode the number from a float, which is commonly 4 bytes.

std::string double_to_hex_string(double d)
{
    // Create a stream that writes 2 digit hex values
    std::stringstream stream;
    stream << std::hex << std::setfill('0');

    float f = d;
    const unsigned char *buffer = reinterpret_cast<unsigned char*>( &f );
    const unsigned char *buffer_end = buffer + sizeof(f);

    // Write each byte as 2 character hex.
    while ( buffer != buffer_end )
    {
      stream << std::setw(2) << static_cast<int>( *buffer );
      ++buffer;
    }

    return stream.str();
}
于 2013-03-21T16:45:54.197 回答