Giriş
#pragma pack(N) data alignment için en portable yöntem
1 Byte Padding
Örnek
Şöyle yaparız:
#pragma pack(push, 1)
typedef struct {
unsigned char __reserved : 1;
unsigned char dont_fragment : 1;
unsigned char more_fragment : 1;
unsigned short fragment_offset : 13;
} ipv4_fragmenting;
#pragma pack(pop)
Örnek
Şöyle yaparız.
#pragma pack(push, 1)
struct Sensor1Telemetry {
int16_t temperature;
uint32_t timestamp;
uint16_t voltageMv;
// etc...
};
#pragma pack(pop)
Örnek
Şöyle yaparız
int main() {
#pragma pack(push, 1)
struct align1 {
struct {
double d; // 8 bytes
bool b1; //+1 byte (+ 0 bytes padding) = 9 bytes
} subStruct;
bool b2; //+1 byte (+ 0 bytes padding) = 10 bytes
char pad_[6]; //+6 bytes (+ 0 bytes padding) = 16 bytes
};
#pragma pack(pop)
struct align2 {
double d; // 8 bytes
bool b1, b2; //+2 byte (+ 6 bytes padding) = 16 bytes
};
std::cout << "align1: " << sizeof(align1) << " bytes\n"; // 16 bytes
std::cout << "align2: " << sizeof(align2) << " bytes\n"; // 16 bytes
return 0;
}
Çıktı olarak şunu alırız
align1: 16 bytes align2: 16 bytes
Örnek
Şöyle yaparız
#pragma pack(push,4)
struct MyStruct
{
uint32_t i1; /* offset=0 size=4 */
uint32_t i2; /* offset=4 size=4 */
uint16_t s1; /* offset=8 size=2 */
unsigned char c[8]; /* offset=10 size=8 */
uint16_t s2; /* offset=18 size=2 */
uint16_t s3; /* offset=20 size=2 */
/* offset=22 padding=2 (needed to align MyStruct) */
} ; // total size is 24
Hiç yorum yok:
Yorum Gönder