我正在用这个函数打包我的字符串:
std::vector<char> pack(const std::string& str) {
const uint32_t sz = str.size();
const uint32_t n_sz = htonl(sz);
std::vector<char> result(sizeof(sz) + sz);
memcpy(result.data(), &n_sz, sizeof(n_sz));
memcpy(result.data() + sizeof(sz), str.data(), sz);
return result;
}
我怎样才能再次解压它,以便...我得到原来的字符串?
我尝试过:
int len;
len = ntohl(ourbuffer.size());
char* string = ( char* )malloc(sizeof (char) * (len + 1));
string[len] = '\0';
因为我知道功能包使用大端。但这没有用。有人可以告诉我如何再次解压吗??
最佳答案
uint32_t n_sz;
memcpy(&n_sz, ourbuffer.data(), sizeof n_sz);
const uint32_t sz = ntohl(n_sz);
std::string str(ourbuffer.data() + sizeof n_sz, sz);
关于C++:再次解压数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49272216/