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

痞子三分冷 提交于 2020-01-04 04:34:11

问题


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++


回答1:


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), i.e. 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



回答2:


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.)




回答3:


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();
}


来源:https://stackoverflow.com/questions/17964859/c-convert-array-of-floats-to-stdstring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!