Is there any way, to not use the padding or to skip the padded bytes when writing to a file?

Is there any way, to not use the padding or to skip the padded bytes when writing to a file?



I'm working with an ARM processor Cortex-m4, STM32L476RG Board.



I have read about the padding might be the reason to a bigger size of the struct, than what actually inside the struct.



But, I would really like to get the exact size of 68 bytes to the struct instead of 72.



Anyone have an idea on how to get the right sizee?



Consider the following struct:


struct data

double Latitude; // 00-07
double Longtitude; // 08-15
float HorizontalAcc; // 16-19
float Altitude; // 20-23
float AltitudeAcc; // 24-27
float SpeedInMS; // 28-31
float SpeedAcc; // 32-35
float Heading; // 36-39
float HeadingAcc; // 40-43
int Data; // 44-47
unsigned long PacketNumber; // 48-51
int64_t y; // 52-59
int64_t x; // 60-67
; // size 8 + 8 + 7*4 + 4 + 4 + 8 + 8 = 68



The thing is that I need to write these data bytewise into a binary file, and the padding ( after PacketNumber ) ruining it.. Is there anyway, to not use the padding or maybe to skip the padded bytes when writing to a file?





because of padding.
– Jean-François Fabre
May 28 at 13:50





I was looking for a solution, not a why... sad this is going to be a duplicate to a question there is only a why... as I explained in the question.. I know why, but I dont know how to get the right size
– Noob14
May 29 at 9:27





try reordering the datatypes by size. Ex: move the int64_t after the double, that should reduce/remove the padding
– Jean-François Fabre
May 29 at 9:39


int64_t


double





VisualC has a pragma to turn off padding. #pragma pack(1) Your compiler might have something similar.
– Serve Laurijssen
May 29 at 9:41





Not in a standard way, but ordering fields from strictest to most relaxed alignment usually minimises padding and moves all of it to the end of the struct. If this is not enough, and your compiler doesn't provide a way to turn packing on, you have to serialize your data manually field by field.
– n.m.
May 29 at 9:51





2 Answers
2


#pragma pack(x)



is the solution and fixed my problem.
In this case with either 4 or 8 bytes, I chose #pragma pack(4).


#pragma pack(4)



gcc users can also use non-standard __attribute__ ((packed)) attribute for remove padding from the wanted struct:


__attribute__ ((packed))


struct data

double Latitude; // 00-07
...
unsigned long PacketNumber; // 48-51
int64_t y; // 52-59
int64_t x; // 60-67
__attribute__ ((packed));






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)