utvecklare utvecklare - 1 month ago 17
C++ Question

Parsing buffer data in C++

My C++ project has a buffer which could be any size and is filled by Bluetooth. The format of the incoming messages is like 0x43 0x0B 0x00 0x06 0xA2 0x03 0x03 0x00 0x01 0x01 0x0A 0x0B 0x0B 0xE6 0x0D in which starts with 0x43 and ends with 0x0D. So, it means that each time when buffer is filled, it can have different order of contents according to the above message format.

static const int BufferSize = 1024;
byte buffer[BufferSize];



  1. What is the best way to parse the incoming messages in this buffer?

  2. Since I have come from Java and .NET, What is the best way to make each extracted message as an object? Class could be solution?

  3. I have created a separate class for parsing the buffer like bellow, am I in a right direction?






#include<parsingClass.h>
class A
{
parsingClass ps;
public:
parsingClass.parse(buffer, BufferSize);
}

Answer

My C++ project has a buffer which could be any size

The first thing I notice is that you have hard-coded the buffer size. You are in danger of buffer overflow if an attempt is made to read data bigger than the size you have specified into the buffer.

If possible keep the buffer size dynamic and create the byte array according to the size of the data to be received into the buffer. Try and inform the object where your byte array lives of the incoming buffer size, before you create the byte array.

int nBufferSize = GetBufferSize();
UCHAR* szByteArray = new UCHAR[nBufferSize];

What is the best way to parse the incoming messages in this buffer?

You are on the right lines, in that you have created and are using a parser class. I would suggest using memcpy to copy the individual data items one at a time, from the buffer to a variable of your choice. Not knowing the wider context of your intention at this point, I cannot add much to that.

Since I have come from Java and .NET, What is the best way to make each extracted message as an object? Class could be solution?

Depending on the complexity of the data you are reading from the buffer and what your plans are, you could use a class or a struct. If you do not need to create an object with this data, which provides services to other objects, you could use a struct. Structs are great when your need isn't so complex, whereby a full class might be overkill.

I have created a separate class for parsing the buffer like bellow, am I in a right direction?

I think so.

I hope that helps for starters!

Comments