警告:以下代碼使用當前平臺的endian來混淆數據。如果您將此發送給其他可能沒有相同的endian和其他相關體系結構參數的平臺,請小心。
我打算假設你明白你在做什麼是將float的4個字節放到字符串的內存中,而不是float的字符串表示形式。例如,對於整數值爲2的字符串,將char值'\ 0','\ 0','\ 0','\ 2'放入字符串中。這與'002'作爲一個常規的人類可讀字符串(第一個是3個空終止符加上一個小數值爲2的字符)是不一樣的。你也是直接將float的二進制表示注入到字符串中。
如果這就是你想要的,那麼你最好使用除字符串以外的東西來存儲值(maybe a std::vector<char>
/std::vector<unsigned char>
)。例如:
std::vector<char>& encode_foo(const foo &input) {
// Note that these loops, as @DeadMG pointed out in comments, can be
// more easily accomplished with vector.insert(...), e.g.:
// vector.insert(vector.end(), adata, adata + sizeof(input.a));
std::vector<char> data;
char* adata = (char*)&input.a;
char* bdata = (char*)&input.b;
char* cdata = (char*)input.c.data();
for (int i = 0; i < sizeof(input.a); ++i) {
data.push_back(*adata);
++adata;
}
for (int j = 0; j < sizeof(input.b); ++j) {
data.push_back(*bdata);
++adata;
}
for (int k = 0; k < input.c.length(); ++k) {
data.push_back(*cdata);
++cdata;
}
// Now, data contains the absolute minimum binary
// representation of the structure
// There are probably even simpler ways to do this,
// but the 3 loops are very explicit
// And demonstrate what you want.
// You could consider std::copy or memcpy instead if you need
// More flexibility.
return data;
}
foo decode_foo(const std::vector<char>& input) {
// Because you know the structure ahead of time, you can simply reverse the process
// Here, I'll use memcpy to show how that's used too
foo datafoo;
memcpy(datafoo.a, input.data(), sizeof(datafoo.a));
// Offset by 4 (which is the typical size of an int
memcpy(datafoo.b, input.data() + sizeof(datafoo.a), sizeof(datafoo.b));
// Now, we offset by 8, and each byte represents a character
// We can memcpy into a std::string's data and null-terminate it as needed
// By calling resize and telling it it's as big as the leftover data
// minus the size of the other structures
int offset = (sizeof(datafoo.a) + sizeof(datafoo.b));
int csize = input.size() - offset;
datafoo.c.resize(csize);
memcpy(datafoo.c.input.data(), input.data() + offset, csize);
// Usually, you don't use memcpy with strings,
// but this should do exactly as you want
return datafoo;
}
這應該不是「浪費任何字節或空間」,按照您的要求,但請記住,你應該使用std::vector<char>
爲您的存儲,如果你想有一個二進制表示。另外,請查看protobuff等數據打包和數據傳輸協議。您也可以使用上面的std :: string,但請記住,使用上面的一些修改的std :: string會使該字符串在很多程序和例程中表現不佳,因爲strings
預計爲null終止,並在C++中的數字的二進制表示將皇家擰你的。
爲什麼不使用JSON? – 2013-02-27 19:19:23
查找['std :: to_string'](http://en.cppreference.com/w/cpp/string/basic_string/to_string),並使用分隔符。 – 2013-02-27 19:19:27
我不想浪費更多的位......我的理解是,std :: to_string會使它更大,假設我的float是1.111111111,我只想花費4個字節。 – WhatABeautifulWorld 2013-02-27 19:22:57