您认为在c ++中解析固定长度消息的最快或最好的方法是什么,其中字段定义为
field = 'type', length = 2, type = 'alphanumeric'
field = 'length', length = 2, type = 'binary' (edit:length = 2 means 16 bit)
...
...
and so on
我读过关于创建一个结构然后使用reinterpret_cast但我不确定如何使用它或者是否有更好的方法。
通过解析,我的意思是提取人类可读的格式,如'Type = X','Length = 15'等
答案 0 :(得分:2)
这是你的意思吗?
char* binaryMessage; //From somewhere
struct Fields {
short type; // 2 bytes
short length; // 2 bytes
};
Fields* fields = reinterpret_cast<Fields*>(binaryMessage);
std::cout << "Type = " << fields->type;
std::cout << "Length = " << fields->length;
更安全的替代方案是boost::basic_bufferstream
:
basic_bufferstream<char> stream(binaryMessage, lengthOfMessage, std::ios_base::in);
Fields fields;
stream >> fields.type;
stream >> fields.length;