I have to work on an prop. binary file format and want to realize it with the use of structs.
I need constant byte sequence in my structs and atm I don't get it how to realize that.
I thought about something like that:
#include <cstdint>
#pragma pack(push,1)
typedef struct PAYLOAD_INFO {
const uint8_t magicnumber[4] = { 0xFA, 0x11 , 0x28 , 0x33 };
uint16_t UMID;
const uint16_t VID = 1487 ;
uint32_t crc;
};
#pragma pack(pop)
int main (){
PAYLOAD_INFO pldInst;
pldInst.UMID = 5;
pldInst.crc = 0x34235a54;
...
writeToFile(&PAYLOAD_INFO,sizeof(PAYLOAD_INFO));
}
In the end "pldInst" should look some like that ( in the memory) , without regard of the byteorder in this example:
0x00000000: 0xFA, 0x11 , 0x28 , 0x33
0x00000004: 0x00, 0x05 , 0x05 , 0xCF
0x00000008: 0x34, 0x23 , 0x5a , 0x54
I already tried the "default" approach:
#include <cstdint>
#pragma pack(push,1)
typedef struct PAYLOAD_INFO {
static const uint8_t magicnumber[4];
uint16_t UMID;
static const uint16_t VID = 1487 ;
uint32_t crc;
};
const uint8_t magicnumber[4] = { 0xFA, 0x11 , 0x28 , 0x33 };
#pragma pack(pop)
but doesn't work as intend.
Is there a way to get this done without calculating the memory size of every struct member,allocating new memory and copying every member ?
I using g++ 4.6.3.
Regard, Thomas
UPDATE:
The the c++11 solution provided by @bikeshedder works very well but it compiles only with g++ 4.7 or higher.