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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值