字节对齐

来源:互联网 发布:电脑软件培训学校 编辑:程序博客网 时间:2024/05/17 04:27

让编译系统生成字节对齐的code,有两种方法:

一、

struct bmp_filehead
{
 char bmpid[2];  /*BM*/
 unsigned int filesize; /*file size*/
 unsigned int reserved1; /*must be 0L*/
 unsigned int imgoff; /*general 54L*/
 unsigned int headsize; /*40L*/
 unsigned int imgwidth;
 unsigned int imgheight;
 unsigned short planes; /*must be 1L*/
 unsigned short bitcount;
 unsigned int compression;
 unsigned int datasize;
 unsigned int hres;
 unsigned int vres;
 unsigned int colors;
 unsigned int impcolors;
}__attribute__((packed,aligned(1)));

 

二、

#pragma pack(1)

struct bmp_filehead
{
 char bmpid[2];  /*BM*/
 unsigned int filesize; /*file size*/
 unsigned int reserved1; /*must be 0L*/
 unsigned int imgoff; /*general 54L*/
 unsigned int headsize; /*40L*/
 unsigned int imgwidth;
 unsigned int imgheight;
 unsigned short planes; /*must be 1L*/
 unsigned short bitcount;
 unsigned int compression;
 unsigned int datasize;
 unsigned int hres;
 unsigned int vres;
 unsigned int colors;
 unsigned int impcolors;
};

#pragma pack

有时,

#pragma pack不为编译系统所支持,特别是某些arm-linux-gcc编译工具。因此,建议用第一种方式。