天天看点

C语言中字节对齐问题( Byte Order Problem)

                                               Byte Order Problem

 A short int consists of 2 bytes. Consider the number 0X1234. The 2 bytes have the values 0X12 and 0X34. Which value is stored in the first byte? The answer is machine dependent.

This uncertainty can cause considerable trouble when you are trying to write portable binary files. The Motorola 68000-series machines use one type of byte order(ABCD), while Intel and Digital Equipment Corporation machines use another (BADC).

One solution to the problem of portable binary files is to avoid them. Put an option in your program to read and write ASCII files. ASCII offers the dual advantages of being far more portable and human readable.

The disadvantage is that text files are larger. Some files may be too big for ASCII. In that case, the magic number at the beginning of a file may be useful. Suppose the magic number is 0X11223344(a bad magic number, but a good example). When the program reads the magic number, it can check against the correct number as well as the byte-swapped version(0X22114433). The program can automatically fix the file problem:

const long int MAGIC = 0X11223344L //file identification number

const long int SWAP_MAGIC =0X22114433L //magic-number byte swapped

FILE *in_file;

long int magic;

in_file=fopen("data","rb");

fread((char *)&magic,sizeof(magic),1,in_file);

switch(magic)

{

     case MAGIC: break; //No problem

    case SWAP_MAGIC: printf("Converting file, please wait\n");

                                        convert_file(in_file);

                                       break;

    default:

         fprintf(stderr, "Error: bad magic number %lx\n",magic); exit(8);

}

继续阅读