I am parsing a binary header (std::vector<unsigned char>
) and need to extract four unsigned integers.
I will also sometimes need to extract unsigned short
as well (for other headers) so generic solutions are preferable.
How can I convert a slice of a std::vector into a integer?
Here is what I've tried:
class PacketHeader {
public:
static const unsigned short LENGTH = 16;
PacketHeader(std::vector<unsigned char> &binary_data) {
this->timestamp_seconds = ntohs(*reinterpret_cast<const unsigned int *>(&binary_data[0]));
this->timestamp_ms_or_ns = ntohs(*reinterpret_cast<const unsigned int *>(&binary_data[4]));
this->packet_data_length = ntohs(*reinterpret_cast<const unsigned int *>(&binary_data[8]));
this->untruncated_packet_data_length = ntohs(*reinterpret_cast<const unsigned int *>(&binary_data[12]));
}
unsigned int get_timestamp_seconds();
unsigned int get_timestamp_ms_or_ns();
unsigned int get_packet_data_length();
unsigned int get_untruncated_packet_data_length();
private:
unsigned int timestamp_seconds;
unsigned int timestamp_ms_or_ns;
unsigned int packet_data_length;
unsigned int untruncated_packet_data_length;
};