zoukankan      html  css  js  c++  java
  • C语言的Bit fields

    C语言给我们提供了几个基本的数据类型,比如char(8位),short(16位),int(32位),long long(64位)。然而实际应用中,这些数据类型的变量一般都不会“存满”,这样从信息存储的效率的角度上讲,这是一种“浪费”。好在C语言在结构体中引入了Bit fields这种数据结构,可以在一定程度上减小结构体的大小,提高内存使用效率。

    Bit fields可以指定某个结构体变量所占用的位数(指定的位数必须比小于等于这个变量的数据类型占用的位数),从而达到减少使用空间的目的。

    书写格式为:

    struct 位域结构名

    {

      位域列表

    };

    其中位域列表的形式为:

     类型说明符 位域名:位域长度;

    例如:

    struct time{
         int day:5,
          mouth:4,
          year:14;
    };

    在这里,day这个变量所占用的空间就是5位,mouth是4位,year位14位。

     这里我们假设要通过定义结构体来表示日期,我们来试一下使用Bit fields可以节约多少空间。

    因为一个月最多只有31天,所以用5bit就可以表示这个信息。

    同理,月数需要4bit,年数(假设四位数,0-9999)需要14bit。

     1 #include <cstdio>
     2 
     3 struct time{
     4     int day:5,
     5     mouth:4,
     6     year:14;
     7 };
     8 struct time2{
     9     int day,
    10     mouth,
    11     year;
    12 };
    13 
    14 int main()
    15 {
    16     time now;
    17     time2 now2;
    18     now.day=3;
    19     now.mouth=1;
    20     now.year=2016;
    21     now2.day=3;
    22     now2.mouth=1;
    23     now2.year=2016;
    24     printf( "%d %d %d
    ",now.year,now.mouth,now.day );
    25     printf( "%d %d %d
    ",now2.year,now2.mouth,now2.day );
    26     int structsize=sizeof( now );
    27     printf( "the size of struct time is %d
    ",structsize );
    28     int structsize2=sizeof( now2 );
    29     printf( "the size of struct time2 is %d
    ",structsize2 );
    30     return 0;
    31 }

    运行结果为

    从中可以看出,Bit fields确实可以压缩结构体的大小,这个存储时间信息的结构体便可以压缩到平时(普通int定义)大小的1/3.这在一些算法以及大型软件开发中会有很大用处。

    然而。。我通过发现Bit fields定义的不同变量类型的结构体依然还是会遵循内存对齐。。所以Bit fields也就只能对只有相同的结构体变量的结构体起作用了。。

     1 #include <cstdio>
     2 
     3 struct bit{
     4    char x:2;
     5    int y:6;
     6    long long z:10;
     7 };
     8 int main()
     9 {
    10     bit t;
    11     int structbit=sizeof( t );
    12     printf( "the size of struct structbit is %d
    ",structbit );
    13     return 0;
    14 }

    运行结果:

    这个结构体占用的空间依然是遵循内存对齐的4+4+8=16字节

  • 相关阅读:
    java方式实现堆排序
    java方式实现归并排序
    用java方式实现快速排序
    Linux中crontab定时任务
    TCP/IP网络协议初识
    github设置添加ssh
    IDM下载工具使用
    Java程序在内存中运行详解
    GitHub的高级搜索方式
    深入理解JavaScript中的堆与栈 、浅拷贝与深拷贝
  • 原文地址:https://www.cnblogs.com/kiwibird/p/5095712.html
Copyright © 2011-2022 走看看