将 bool[] 转换为 std::string 的 void*

void* of a bool[] conversion to std::string

本文关键字:string void std bool 转换      更新时间:2023-10-16

我需要保存一些数据,唯一可行的选择是std::string;所以我得到了一个作为void*传递的布尔数组。现在我需要以一种可以将其转换为std::string并能够从该确切字符串中读取void*bool[]的方式保存它。可悲的是,我在皈依中迷失了方向。

f(const void* data, int length){
   bool** boolPointer = (bool**)(data);
   bool boolArray[length];
   for (int i=0; i<=length; i++){
       boolArray[i] = p[sizeof(bool)*i];
   }
   std::string s = (std::string&)boolArray;
}

我很确定最后一行是不可行的转换,但这是我的尝试。

这对你有用吗?

char f(bool b)
{
    return b ? '1' : '0';
}
int main()
{
    // let's just consider whatever is there in this uninitialized array
    bool buf[100];
    std::string s;
    // transform and copy (convert true to '1' and false to '0')
    std::transform(&buf[0], &buf[99], std::back_inserter(s), f);
    std::cout << s << std::endl;
}

如果您使用的是 C++11,则可以使用以下代码片段

int main()
{
    bool buf[100];
    std::string s;
    std::transform(&buf[0], &buf[99], std::back_inserter(s), [](bool const &b){ return b ? '1' : '0'; });
    std::cout << s << std::endl;
}

您可以重载输出运算符以将布尔值转换为您想要的任何值:

ostream& operator<<(const ostream& os, const bool& value) {
    return os << (value ? "1" : "0");
}

然后将数组复制到stringstream

int main() {
    // ...
    ostringstream oss;
    copy(data, data+size, ostream_iterator<bool>(oss));
    oss.str(); // this is the string you're looking for
    // ...
}

好吧,我想你可以打开你的C++书......

std::string f(std::vector<unsigned char> const& v)
{
    std::string temp;
    for (auto c : v) {
        for (unsigned i = 0; i < 8; ++i) {
            temp += (c & (1 << i)) ? '1' : '0';
        }
    }
    return temp;
}

使用std::copy或其他一些神秘back_inserter的东西,这可能更容易完成,但我想保持简单。另一种选择是使用std::bitset或您自己的封装来摆脱丑陋的位操作。

如果你被魔鬼强迫通过void*传递数据,只需将其转换为矢量:

unsigned char* begin = static_cast<unsigned char*>(data);
vector<unsigned char> v (begin, begin + length);

另请注意,如果出于序列化目的,计算机和人类都很难读取该表示形式。如果它要由计算机读取,请将其另存为二进制文件而不进行转换。如果它要由人类读取,请将其另存为十六进制字符(将每个字节分成两半)。

相关文章: