我有这个消息文件:
message samplemessage
{
optional bytes byte_string = 1;
}
以及使用此 protobuf 文件的程序:
#include <iostream>
#include <fstream>
#include <string>
#include "mymessages.pb.h"
using namespace std;
// Main function: Reads the entire packet from file,
// modifies the string_data field and then writes the modified version back to disk.
void print_hex2(const char* string, int length) {
for (int i = 0; i<length;i++) {
printf("%02x", (unsigned int) *string++);
}
printf("\n");
}
int main(int argc, char* argv[]) {
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
if (argc != 3) {
cerr << "Usage: " << argv[0] << " PACKET_FILE OUTPUT_FILE" << endl;
return -1;
}
samplemessage thing;
{
// Read the existing address book.
fstream input(argv[1], ios::in | ios::binary);
if (!input) {
cout << argv[1] << ": File not found. Creating a new file." << endl;
} else if (!thing.ParseFromIstream(&input)) {
cerr << "Failed to parse packet file." << endl;
return -1;
}
}
print_hex2(thing.byte_string().c_str(), strlen(thing.byte_string().c_str()));
printf("%s\n", thing.byte_string().c_str());
unsigned char stuff[10000] = "\x41\x80";
thing.set_byte_string(reinterpret_cast<const unsigned char *>(stuff));
printf("%s\n", thing.byte_string().c_str());
print_hex2(thing.byte_string().c_str(), strlen(thing.byte_string().c_str()));
{
// Write the new packet to disk.
fstream output(argv[2], ios::out | ios::trunc | ios::binary);
if (!thing.SerializeToOstream(&output)) {
cerr << "Failed to write packet file." << endl;
return -1;
}
}
// Optional: Delete all global objects allocated by libprotobuf.
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
这个程序编译后为我生成这个输出:
41ffffff80
但是当我将
\x80
更改为 \x7f
时,ff 值没有出现,我得到了这个输出:
417f
用 xxd 查看输出文件,我在任何地方都看不到这些 ff 字节:
00000000: 0a02 4180 ..A.
这是为什么?这是一些编码的东西吗?我认为 protobuf 中的字节编码原始字节,但显然这里不是这种情况?为什么要添加 ff 字节?
提前致谢!
printf("%02x", (unsigned int) *string++);
显然
char
在你的平台上签名,这很常见。
然后当你施放
(unsigned int)((char)0x80))
时,0x80
被评估为-128
并首先扩展为int
。结果为0xffffff80
试试这个:
printf("%02x", (unsigned int)(unsigned char) *string++);