分享

4字节对齐

 web127 2013-04-27

BMP图四字节对齐的问题

  1、内存分配单位是32位的,即4字节;  
  2、位图中每行象素的数据是连续的,而下一行不能和上一行共一个分配单元(4字节),所以每行象素的数据长度必须是4字节的倍数;  
  3、代码说明如下:  
         
  int     WidthBytes(   int   nBits,   int   nWidth   )  
  {//nBits为色彩位数,   nWidth为每行象素个数  
  int   nWidthBytes;//每行象素的数据长度  

  nWidthBytes   =   nWidth;  
  if(   nBits   ==   1   )   nWidthBytes   =   (   nWidth   +   7   )   /   8;  
  else   if(   nBits   ==   4   )   nWidthBytes   =   (   nWidth   +   1   )   /   2;      /*竟然没有8位的。256色不是很常见吗?!*/
  else   if(   nBits   ==   16   )   nWidthBytes   =   nWidth   *   2;  
  else   if(   nBits   ==   24   )   nWidthBytes   =   nWidth   *   3;//24位真彩色  
  else   if(   nBits   ==   32   )   nWidthBytes   =   nWidth   *   4;//32位真彩色  
   
  //*******四字节对齐*******  
  while(   (   nWidthBytes   &   3   )   !=   0   )   nWidthBytes++;  
  //*******四字节对齐*******  
  return(   nWidthBytes   );  

  }   

--------------------------------------------------------------------------------------------------------------------------

我的理解:

1.bmp为4字节的方式,因此在buf中,不论存取还是显示,都是以4字节为单位的。

2.接下来的问题就是怎么确定一行到底要怎么对齐。

首先,int 的除法。结果还是int,会舍掉小数点。所以。我们加上3字节。再除以4。就可以防止字节数变少

eg:Width=1(位图的宽度为1像素) BitCount=24(24位的像素位数。1个像素24位即3字节)

       Width*BitCount/8=3得出占用的字节数是3.

       (3+3)/4  这是求出“基数”,为1.  如果没有加上3的话,商为0,明显不符合题意。

         1*4得出LineBytes=4.

同理,如果是以位为单位,就是加上31.   Width*BitCount+31

  then: (Width*BitCount+31)/32  *4

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多