Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replicating C struct padding in Java

According to here, the C compiler will pad out values when writing a structure to a binary file. As the example in the link says, when writing a struct like this:

struct {
 char c;
 int i;
} a;

to a binary file, the compiler will usually leave an unnamed, unused hole between the char and int fields, to ensure that the int field is properly aligned.

How could I to create an exact replica of the binary output file (generated in C), using a different language (in my case, Java)?

Is there an automatic way to apply C padding in Java output? Or do I have to go through compiler documentation to see how it works (the compiler is g++ by the way).

like image 876
Lehane Avatar asked Nov 27 '22 02:11

Lehane


1 Answers

Don't do this, it is brittle and will lead to alignment and endianness bugs.

For external data it is much better to explicitly define the format in terms of bytes and write explicit functions to convert between internal and external format, using shift and masks (not union!).

like image 162
starblue Avatar answered Dec 04 '22 21:12

starblue