C/C++ 位域(Bit Fields)

來源:互聯網
上載者:User

今天中午與同事討論位域的問題,越討論越迷糊,最終還是求救Google,找到一些文章,把比較好兩篇的轉載於下。

 

 

 

1. 原文:http://www.cs.cf.ac.uk/Dave/C/node13.html

 

 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!!.)

 

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

 

 Bitwise operators Table:
& AND
OR
XOR
One's Compliment
 
 
<< Left shift
>> Right Shift


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

 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 NOwrap 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: 

 or 0 (decimal) 

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

 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. 

int bitcount(unsigned char x) { int count; for (count=0; x != 0; x>>=1) if ( x & 01) count++; return count; } 

 

This function illustrates many C program points: for loop not used for simple counting operation x 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++

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. 

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  flag.

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)    ......  }

 

 

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;

 

 

Exercise 12507

Write a function that prints out an 8-bit (unsigned char) number in binary format.

 

Exercise 12514

Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of an unsigned char variable y (leaving other bits unchanged).

E.g. if x = 10101010 (170 decimal) and y = 10100111 (167 decimal) and n = 3 and p = 6 say then you need to strip off 3 bits of y (111) and put them in x at position 10xxx010 to get answer 10111010.

Your answer should print out the result in binary form (see Exercise 12.1 although input can be in decimal form.

Your output should be like this:

 

   x = 10101010 (binary)   y = 10100111 (binary)   setbits n = 3, p = 6 gives x = 10111010 (binary)

 

 

 

Exercise 12515

Write a function that inverts the bits of an unsigned char x and stores answer in y.

Your answer should print out the result in binary form (see Exercise 12.1 although input can be in decimal form.

Your output should be like this:

 

   x = 10101010 (binary)   x inverted = 01010101 (binary)

 

 

 

Exercise 12516

Write a function that rotates (NOT shifts) to the right by n bit positions the bits of an unsigned char x.ie no bits are lost in this process.

Your answer should print out the result in binary form (see Exercise 12.1 although input can be in decimal form.

Your output should be like this:

 

   x = 10100111 (binary)   x rotated by 3 = 11110100 (binary)

 

 

 

Note: All the functions developed should be as concise as possible 2. 原文: http://msdn.microsoft.com/en-us/library/ewwyfdbe(v=vs.71).aspx

Classes and structures can contain members that occupy less storage than an integral type. These members are specified as bit fields. The syntax for bit-fieldmember-declarator specification follows: Copy

declaratoropt  : constant-expression

The declarator is the name by which the member is accessed in the program. It must be an integral type (including enumerated types). The constant-expressionspecifies the number of bits the member occupies in the structure. Anonymous bit fields — that is, bit-field members with no identifier — can be used for padding. Note   An unnamed bit field of width 0 forces alignment of the next bit field to the next  type boundary, where  type is the type of the member.

The following example declares a structure that contains bit fields: Copy

// bit_fields1.cppstruct Date{   unsigned nWeekDay  : 3;    // 0..7   (3 bits)   unsigned nMonthDay : 6;    // 0..31  (6 bits)   unsigned nMonth    : 5;    // 0..12  (5 bits)   unsigned nYear     : 8;    // 0..100 (8 bits)};int main(){}

The conceptual memory layout of an object of type Date is shown in the following figure.

Memory Layout of Date Object

Note that nYear is 8 bits long and would overflow the word boundary of the declared type, unsigned int. Therefore, it is begun at the beginning of a newunsigned int. It is not necessary that all bit fields fit in one object of the underlying type; new units of storage are allocated, according to the number of bits requested in the declaration.

Microsoft Specific

The ordering of data declared as bit fields is from low to high bit, as shown in the figure above.

END Microsoft Specific

If the declaration of a structure includes an unnamed field of length 0, as shown in the following example, Copy

// bit_fields2.cppstruct Date{   unsigned nWeekDay  : 3;    // 0..7   (3 bits)   unsigned nMonthDay : 6;    // 0..31  (6 bits)   unsigned           : 0;    // Force alignment to next boundary.   unsigned nMonth    : 5;    // 0..12  (5 bits)   unsigned nYear     : 8;    // 0..100 (8 bits)};int main(){}

the memory layout is as shown in the following figure.

Layout of Date Object with Zero-Length Bit Field

The underlying type of a bit field must be an integral type, as described in Fundamental Types.

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.