zoukankan      html  css  js  c++  java
  • 字节对齐

    广义的二进制文件分为文本文件和狭义的二进制文件(简称二进制文件)。

    文本文件的特点是基于定长编码的,二进制文件是变长编码的,特点是多少比特代表的值是完全由我们决定的。

    二进制文件中一种比较特殊的情形就是保存相同类型的数据结构的多个值。

    例如结构体:

    struct file_test
    {
            int i;
            char c;
            short s;
    };

    写入文件

    #include <stdio.h>
    #include <fcntl.h>
    struct file_test
    {
            int i;
            char c;
            short s;
    };
    
    int main ()
    {
            struct file_test file_test_value;
            int fd;
            file_test_value.i = 1;
            file_test_value.c = 'c';
            file_test_value.s = '2';
    
            if ( (fd = open("/home/yang/documents/unix/2_chapter/test", O_WRONLY)) == -1 )
            {
                    perror("open");
                    return -1;
            }if ( write(fd, &file_test_value, sizeof(file_test_value)) == -1 )
            {
                    perror("write");
                    return -1;
            }
    
            close(fd);
    
            printf("the sizeof struct: %d\n",sizeof(file_test_value));
            return 0;
    }

    查看写入的信息

    yang@UbuntuPc:~/documents/unix/2_chapter$ hexdump test 
    0000000 0001 0000 0063 0032                    
    0000008

    而如何写入与编译器相关

    如果添加下来这句话则,写入的信息为

    #pragma pack(1)
    yang@UbuntuPc:~/documents/unix/2_chapter$ hexdump test 
    0000000 0001 0000 3263 0000                    
    0000008

    采用不同的对其方式,编译器保存的其实位置就不同

    字节对齐:http://www.cnblogs.com/logogcn/archive/2010/11/30/1891699.html

    几个概念:

    1.数据类型自身的对齐值:
       对于char型数据,其自身对齐值为1,对于short型为2,对于int,float,double类型,其自身对齐值为4字节

    2.结构体或者类的自身对齐值:其成员中自身对齐值最大的那个值。
    3.指定对齐值:#pragma pack (value)时的指定对齐值value。
    4.数据成员、结构体和类的有效对齐值:自身对齐值和指定对齐值中小的那个值。

    有效对齐值N是最终用来决定数据存放地址方式的值,最重要。有效对齐N,就是 表示“对齐在N上”,也就是说该数据的"存放起始地址%N=0".

  • 相关阅读:
    CSS中position小解
    position
    mac默认安装postgresql, 如何让postgresql可以远程访问
    The data directory was initialized by PostgreSQL version 9.6, which is not compatible with this version 10.0.
    active admin gem error
    psql 无法添加超级用户
    ubuntu 15.04 安装Balsamiq Mockups 3
    Rails html 写public里图片的路径
    rails c 历史命令
    undefined local variable or method `per' for []:ActiveRecord::Relation
  • 原文地址:https://www.cnblogs.com/yangqionggo/p/2878702.html
Copyright © 2011-2022 走看看