1

What would you suggest as the fastest or best way to parse a fixed length message in c++ which has fields defined like

field = 'type', length = 2, type = 'alphanumeric'

field = 'length', length = 2, type = 'binary' (edit:length = 2 means 16 bit)
...
...

and so on

I read about making a struct and then using reinterpret_cast but im not sure how to use that or if there is any better method.

By parsing, i mean extracting human readable format like 'Type = X', 'Length = 15' etc

2
  • 1
    If possible, try using a look-up table loaded into memory. Simple comparisons are much faster than decoding. Commented Dec 8, 2009 at 14:29
  • What are the semantics of the binary type? Does length=2 mean any 16-bit quantity or 00-99? Commented Dec 8, 2009 at 14:32

1 Answer 1

2

Is this what you mean?

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;

A safer alternative is boost::basic_bufferstream:

basic_bufferstream<char> stream(binaryMessage, lengthOfMessage, std::ios_base::in);
Fields fields;
stream >> fields.type;
stream >> fields.length;
Sign up to request clarification or add additional context in comments.

1 Comment

This is one way though but is it really safe since reinterpret_cast is considered pretty dangerous to use

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.