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?
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.
because of padding.
– Jean-François Fabre
May 28 at 13:50