Answer the question
In order to leave comments, you need to log in
How to accept and parse UDP QByteArray into a structure from bit fields?
There are 2 bitfield structures combined into one structure. Previously, when the total size of the structure allowed, I did the union through union in uint64. Now the size of the structures has become larger, I transfer it to the QByteArray from the server to the client, and now there is a problem with receiving and parsing.
How do normal people do it right? It is possible with an example, I will be glad!
Answer the question
In order to leave comments, you need to log in
Decided, but not without the help of the community, Thanks.
Structure code:
#pragma pack(push, 1) // работает без директив
struct srt_t // размер структуры 160 бит или 20 байт
{
uint8_t one;
uint8_t two;
uint16_t three;
uint32_t four;
uint64_t five;
uint32_t six;
};
#pragma pack(pop)
srt_t ht{ 255, 255, 65535, 4294967295, 9223372036854775807, 255 };
QByteArray arr;
arr.append( reinterpret_cast<char *>( &ht ), sizeof( ht ) );
srt_t *pDev1 = reinterpret_cast<srt_t *>( arr.data() );
qDebug() << pDev1->one;
qDebug() << pDev1->two;
qDebug() << pDev1->three;
qDebug() << pDev1->four;
qDebug() << pDev1->five;
qDebug() << pDev1->six;
If hypothetically, your program will be portable between different compilers, processors, and architectures, you will have to take into account many nuances:
1) simply copying data from a package to a structure will only work if both machines have the same processor architecture and the same compiler. Otherwise, there may be nuances with the alignment of fields in the structure (it must be disabled) and with the byte storage order (and here problems begin)
2) different processor architectures store integers with different byte order. To avoid conflicts, it is customary to transmit data over the network in network byte order . There are families of functions hton[s|l]/ntoh[s|l] to translate into it. Without them, you will observe terrible glitches.
It follows that you can’t just (tm) copy the bytes that came from the network somewhere, you need to at least convert them from the network order to the host order (and when sending - from the host order to the network), and only then push them into the structure fields ( so the alignment can not be turned off in this case).
Through
reinterpret_cast<char*>(указатель на объект вашей структуры)
get a pointer to an array into which you can write data from QByteArray. #pragma pack(push, 1)
структура
#pragma pack(pop)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question