简体   繁体   中英

C++ - Convert array of floats to std::string

I have an array of floats with a fixed length. Now I want to convert that array to a binary string.

I cannot use const char * because my string will contain null-bytes. How would I use memcpy in that case? I have already tried a reinterpret_cast<string *> , but that won't work because the string is also/only storing pointers to the begin and end of the data (correct me if I am wrong).

I'm already constructing an empty string:

string s;
s.resize(arr_size);

But how would I copy an array of floats to that string?

Basically, I want to dump the memory region of a fixed float array to a string.

Don't be to hard with me, I'm still learning c++

Like this:

#include <algorithm>
#include <string>

float data[10]; // populate

std::string s(sizeof data);
char const * p = reinterpret_cast<char const *>(data);

std::copy(p, p + sizeof data, &s[0]);

Note that sizeof data is the same as 10 * sizeof(float) , ie the number of bytes in the array.

Update: As suggested by James, you can do even better and write it all in one go:

char const * p = reinterpret_cast<char const *>(data);
std::string s(p, p + sizeof data);  // beginning + length constructor

Or even:

#include <iterator>

std::string s(reinterpret_cast<char const *>(std::begin(data)),  // begin + end
              reinterpret_cast<char const *>(std::end(data)));   // constructor

Getting all of the bytes of the array into a string is easy:

std::string
bitwiseDump( float const* begin, float const* end )
{
    return std::string( reinterpret_cast<char const*>( begin ),
                        reinterpret_cast<char const*>( end ) );
}

But why? There's nothing you can do with the string except copy it back into an array of the same type. (And even for that use, std::vector<char> or std::vector<unsigned char> would be more natural. And less obfuscating.)

Take a look at this...

#include <iostream>
#include <array>
#include <string>

int main()
{
    std::string floatString;
    std::array<float, 5> data = {1.1f, 2.2f, 3.3f, 4.4f, 5.5f};

    for (auto& element : data)
        floatString.append(std::to_string(element));

    std::cout << floatString;
    std::cin.get();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM