Search code examples
c++arraysccharstdstring

How can I add a 64 bit floating point number to an unsigned char array at specific indexes (C++)


I need to add a 64 bit floating point number into an unsigned char array at specific indexes (ex. index 1 through 8).

Example unsigned char array:

unsigned char msg[10] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

I want to add a floating point number like 0.084, for example, which is represented as 1B2FDD240681B53F in hex (little endian) to the unsigned char array at indexes 1,2,3,4,5,6,7,8 and leave indexes 0 and 9 unchanged.

So, I would like the unsigned char array, msg, to contain the following:

msg = {0x00, 0x1B, 0x2F, 0xDD, 0x24, 0x06, 0x81, 0xB5, 0x3F, 0x00}

So far I can get a std::string with the hexadecimal representation of the example floating point value 0.084 using the following code but I'm not sure how to add the string values back into the unsigned char array:

#include <iostream>
#include <sstream> 
#include <iomanip>

using namespace std;

int main()
{
    union udoub
    {
        double d;
        unsigned long long u;
    };

    double dVal = 0.084;
    udoub val;
    val.d = dVal;
    
    std::stringstream ss;
    ss << std::setw(16) << std::setfill('0') << std::hex << val.u << std::endl;
    std::string strValHexString = ss.str();
    
    cout<< strValHexString << std::endl;

    return 0;
}

Output: 3fb5810624dd2f1b

I tried using std::copy like in the example below to copy the values from the std::string to an unsigned char but it doesn't seem to do what I want:

unsigned char ucTmp[2];
std::copy(strValHexString.substr(0,2).begin(), strValHexString.substr(0,2).end(), ucTmp);

Looking for a C or C++ solution.


Solution

  • Formatting the component bytes into a hex string and then reading those back in again is a terrible waste of time and effort. Just use std::memcpy() (in C++) or memcpy (in C):

        std::memcpy(&msg[1], &dVal, sizeof(dVal));
    

    This will take care of any required pointer alignment issues. However, it will not do any 'interpretation' in terms of your endianness - but this shouldn't be a problem unless you're then transferring that byte array between different platforms.