将 bool[] 转换为 std::string 的 void*
void* of a bool[] conversion to std::string
我需要保存一些数据,唯一可行的选择是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);
另请注意,如果出于序列化目的,计算机和人类都很难读取该表示形式。如果它要由计算机读取,请将其另存为二进制文件而不进行转换。如果它要由人类读取,请将其另存为十六进制字符(将每个字节分成两半)。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 与'operator='不匹配(操作数类型'String'且"void")
- 错误:"cast"未命名类型void setCastDescription(std::string
- Arduino trim() 和 replace() 方法返回从 'void' 到非标量类型'String'请求的转换
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 如何将 std::string 赋回作为 <char>void* 指针传递的 std::vector.data()?
- 从 'void *' 转换为 'const std::string *&' 必须具有所有中间指针 const 合格
- "conversion from void to non scalar type string"是什么意思?
- 为什么"std::vector<std::string> &"而不是"void"?
- "expected unqualified-id before 'void'" & "string in class does not name a type" 错误
- *&在这里做什么?如何更改它以获取代码作为 void binaryTree::insert(binaryNode *root,string value)?可能吗?
- 函数void()返回一个值,而不是char或string
- C++ 为什么要使用从 (std::string) 到 (void) 类型的隐式转换
- 将 std::function<void(string, string)> 转换为通用 std::function<void()>
- 将内联加速 void a(string b) { cout << b; }
- 将 std::vector<std::string> 转换为 void*
- 将 bool[] 转换为 std::string 的 void*
- C++错误(操作数类型为"std::string 和 'void")
- std::unordered_map<std::string,std::function<void(std::string&) 只能容纳静态函数吗?
- 错误:参数太少,无法函数"void alpha(std::string*,student)"