Low Level Operators and Bit Fields

本文介绍C语言中位操作符的应用及位字段的概念,包括位操作符的使用、位左移与右移实现快速乘除法,以及位字段在结构体中的应用等关键内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Low Level Operators and Bit Fields

  We have seen how pointers give us control over low level memory operations.

Many programs (e.g. systems type applications) must actually operate at a low level where individual bytes must be operated on.

NOTE: The combination of pointers and bit-level operators makes C useful for many low level applications and can almost replace assembly code. (Only about 10 % of UNIX is assembly code the rest is C!!.)

 

Bitwise Operators

The bitwise operators of C a summarised in the following table:

 

 
Table: Bitwise operators
&AND
$/mid$OR
$/wedge$XOR
$/sim$One's Compliment
 $0 /rightarrow 1$
 $1 /rightarrow 0$
<<Left shift
>>Right Shift

 

DO NOT confuse & with &&: & is bitwise AND, && logical AND. Similarly for $/mid$ and $/mid/mid$.

$/sim$ is a unary operator -- it only operates on one argument to right of the operator.

The shift operators perform appropriate shift by operator on the right to the operator on the left. The right operator must be positive. The vacated bits are filled with zero (i.e. There is NO wrap around).

For example: x << 2 shifts the bits in x by 2 places to the left.

So:

if x = 00000010 (binary) or 2 (decimal)

then:

$x /gt/gt= 2 /Rightarrow x = 00000000$ or 0 (decimal)

Also: if x = 00000010 (binary) or 2 (decimal)

$x <<= 2 /Rightarrow x = 00001000$ or 8 (decimal)

Therefore a shift left is equivalent to a multiplication by 2.

Similarly a shift right is equal to division by 2

NOTE: Shifting is much faster than actual multiplication (*) or division (/) by 2. So if you want fast multiplications or division by 2 use shifts.

To illustrate many points of bitwise operators let us write a function, Bitcount, that counts bits set to 1 in an 8 bit number (unsigned char) passed as an argument to the function.

 

This function illustrates many C program points:

  • for loop not used for simple counting operation

    Bit Fields

    Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium. Typical examples:

     

    • Packing several objects into a machine word. e.g. 1 bit flags can be compacted -- Symbol tables in compilers.
    • Reading external file formats -- non-standard file formats could be read in. E.g. 9 bit integers.

    C lets us do this in a structure definition by putting :bit length after the variable. i.e.

    
    struct packed_struct {
    		 unsigned int f1:1;
    		 unsigned int f2:1;
    		 unsigned int f3:1;
    		 unsigned int f4:1;
    		 unsigned int type:4;
    		 unsigned int funny_int:9;
    } pack;
    

     

    Here the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4 bit type and a 9 bit funny_int.

    Bit Fields: Practical Example

    Frequently device controllers (e.g. disk drives) and the operating system need to communicate at a low level. Device controllers contain several registers which may be packed together in one integer (Figure 12.1).

     

    Fig. 12.1 Example Disk Controller Register We could define this register easily with bit fields:

     

    struct DISK_REGISTER  {
         unsigned ready:1;
         unsigned error_occured:1;
         unsigned disk_spinning:1;
         unsigned write_protect:1;
         unsigned head_loaded:1;
         unsigned error_code:8;
         unsigned track:9;
         unsigned sector:5;
         unsigned command:5;
    };
    

    To access values stored at a particular memory address, DISK_REGISTER_MEMORY we can assign a pointer of the above structure to access the memory via:

     

    struct DISK_REGISTER *disk_reg = (struct DISK_REGISTER *) DISK_REGISTER_MEMORY;
    

    The disk driver code to access this is now relatively straightforward:

    /* Define sector and track to start read */
    
    disk_reg->sector = new_sector;
    disk_reg->track = new_track;
    disk_reg->command = READ;
    
    /* wait until operation done, ready will be true */
    
    while ( ! disk_reg->ready ) ;
    
    /* check for errors */
    
    if (disk_reg->error_occured)
      { /* interrogate disk_reg->error_code for error type */
        switch (disk_reg->error_code)
        ......
      }
    

     

    A note of caution: Portability

    Bit fields are a convenient way to express many difficult operations. However, bit fields do suffer from a lack of portability between platforms:

     

    • integers may be signed or unsigned
    • Many compilers limit the maximum number of bits in the bit field to the size of an integer which may be either 16-bit or 32-bit varieties.
    • Some bit field members are stored left to right others are stored right to left in memory.
    • If bit fields too large, next bit field may be stored consecutively in memory (overlapping the boundary between memory locations) or in the next word of memory.

    If portability of code is a premium you can use bit shifting and masking to achieve the same results but not as easy to express or read. For example:

     

    unsigned int  *disk_reg = (unsigned int *) DISK_REGISTER_MEMORY;
    
    /* see if disk error occured */
    
    disk_error_occured = (disk_reg & 0x40000000) >> 31;
    

    C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case then some compilers may allow memory overlap for the fields whilst other would store the next field in the next word (see comments on bit fiels portability below).

    Access members as usual via:

       pack.type = 7;

    NOTE:

    • Only n lower bits will be assigned to an n bit number. So type cannot take values larger than 15 (4 bits long).
    • Bit fields are always converted to integer type for computation.
    • You are allowed to mix ``normal'' types with bit fields.
    • The unsigned definition is important - ensures that no bits are used as a $/pm$ flag.
  • x$/gt/gt=1 /Rightarrow$ x = x >> 1
  • for loop will repeatedly shift right x until x becomes 0
  • use expression evaluation of x & 01 to control if
  • x & 01 masks of 1st bit of x if this is 1 then count++


int bitcount(unsigned char x) 
 
	{ int count;
 
		for (count=0; x != 0; x>>=1)
			if ( x & 01)
			   count++;
		return count;
	}
资源下载链接为: https://pan.quark.cn/s/22ca96b7bd39 在 IT 领域,文档格式转换是常见需求,尤其在处理多种文件类型时。本文将聚焦于利用 Java 技术栈,尤其是 Apache POI 和 iTextPDF 库,实现 doc、xls(涵盖 Excel 2003 及 Excel 2007+)以及 txt、图片等格式文件向 PDF 的转换,并实现在线浏览功能。 先从 Apache POI 说起,它是一个强大的 Java 库,专注于处理 Microsoft Office 格式文件,比如 doc 和 xls。Apache POI 提供了 HSSF 和 XSSF 两个 API,其中 HSSF 用于读写老版本的 BIFF8 格式(Excel 97-2003),XSSF 则针对新的 XML 格式(Excel 2007+)。这两个 API 均具备读取和写入工作表、单元格、公式、样式等功能。读取 Excel 文件时,可通过创建 HSSFWorkbook 或 XSSFWorkbook 对象来打开相应格式的文件,进而遍历工作簿中的每个 Sheet,获取行和列数据。写入 Excel 文件时,创建新的 Workbook 对象,添加 Sheet、Row 和 Cell,即可构建新 Excel 文件。 再看 iTextPDF,它是一个用于生成和修改 PDF 文档的 Java 库,拥有丰富的 API。创建 PDF 文档时,借助 Document 对象,可定义页面尺寸、边距等属性来定制 PDF 外观。添加内容方面,可使用 Paragraph、List、Table 等元素将文本、列表和表格加入 PDF,图片可通过 Image 类加载插入。iTextPDF 支持多种字体和样式,可设置文本颜色、大小、样式等。此外,iTextPDF 的 TextRenderer 类能将 HTML、
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值