简体   繁体   English

C ++ - 将浮点数转换为std :: string

[英]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. 我不能使用const char *因为我的字符串将包含空字节。 How would I use memcpy in that case? 在这种情况下我如何使用memcpy? 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). 我已经尝试过reinterpret_cast<string *> ,但这不起作用,因为字符串也是/只存储指向数据开头和结尾的指针(如果我错了,请纠正我)。

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++ 不要和我一起努力,我还在学习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. 请注意, sizeof data10 * sizeof(float) ,即数组中的字节数。

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.) (甚至对于那种用法, std::vector<char>std::vector<unsigned char>会更自然。而且不那么混淆。)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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