我用这个函数打包我的字符串:
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';
因为我知道功能包正在使用大端。但那没用。有人可以说明如何再打开包装吗?
答案 0 :(得分:1)
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);