Reputation: 1213
I am an absolute beginner to C++ and Qt.
I am broadcasting different data via TCP using Qt. The process of sending and retrieving data works fine but I have problems on interpreting the data on the receivers side.
The data is represented in different structs which have in common that they have a commandId
and a state. The rest could be anything like an error message, a filename or something else. This code is not written on my own and I am not allowed to change it (e.g: define and implement a common interfaces.)
typedef struct
{
uint8_t commandId;
State state;
//special data
QString errorMessage;
} Command1;
typedef struct
{
uint8_t commandId;
State state;
//special data
uint8_t amountSensors;
} Command2;
enum State {
STATID_PAUSE = 50000
STATID_RECORD = 50001
STATID_PLAY = 50002
STATID_ERROR = 50003
}
The sender is converting a struct into a QByteArray
this way:
Command1 example;
example.commandId = 134;
example.state = STATID_ERROR;
char *p_Char;
p_char = reinterpret_cast<char*>(&example);
QByteArray qba(p_char, sizeof(p_char));
Now I have to write a receiver, but the receiver doesn't know what he gets (Command1
, Command2
or something else). He would be able to interpret if he could read out the commandId
and the state.
At this moment I am able to read out the commandId like this:
commandId = static_cast<uint8_t>(qba[0]);
but how could I read out the State
which is an enum
?
Upvotes: 1
Views: 1472
Reputation: 22910
State
values will take the size of an int
. which means to access it you will do :
State state = (State) (*( reinterpret_cast<const int*>(qba.constData()+1)) );
First you reinterpret the const char
pointer as an const int
pointer, then you deference it (which means you obtain the value), and you cast this value as an State
.
In order to access other variables you will start at index 1 + sizeof(int) = 1+ sizeof(State)
See this thread about the size of an enum.
Upvotes: 1