C + + bit field (bit Fields)

Source: Internet
Author: User
Tags bitwise bitwise operators

Today at noon with colleagues to discuss the problem of bit domain, more and more confused, ultimately, or to help Google, find some articles, the comparison of two articles reproduced in the next.

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

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

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

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

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

Bitwise Operators Table:
& and
OR
Xor
One ' s compliment
<< Left shift
>> Right Shift


Don't confuse & with &&: & are bitwise AND, && logical AND. similarly for and.

is a unary operator--it's 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 is 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 are equivalent to a multiplication by 2.

Similarly a shift right are equal to division by 2

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

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

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

This function illustrates many C program Points:for loop not used for simple counting operation x x = x >> 1 for Lo OP would repeatedly shift right x until x becomes 0 use expression evaluation of X & A to control if X & 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 is 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's 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 maximum length of the "field is" less than or equal to the integer word length of the computer. If This isn't the case then some compilers could allow memory overlap for the fields whilst other would store the next Fiel D in the next word ("comments on bit fiels portability below)."

Access members as usual via:

Pack.type = 7;

Note: Only n lower bits is assigned to a n bit number. So type cannot take values larger than (4 bits long). Bit fields are always converted to integer type for computation. You are 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 in a low level. Device controllers contain several registers which of May is packed in one integer (together 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 in a particular memory address, disk_register_memory we can assign a pointer of the above E to access the memory via:

struct Disk_register *disk_reg = (struct disk_register *) disk_register_memory;

The disk driver code to access it 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 would be true

/while (! Disk_reg->ready);

/* Check for errors *

/if (disk_reg->error_occured)
  {/* interrogate Disk_reg->error_code for error type */< C8/>switch (disk_reg->error_code) ...
  }

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

Integers May is signed or unsigned Many compilers limit the maximum number of bits in the bit field to the size of a inte Ger which may be either 16-bit or 32-bit varieties. The Some bit field members are the stored left to right others are stored the right to the left in memory. If bit fields too large, next bit field May is stored consecutively in memory (overlapping the boundary between memory Loc ations) or in the next word of memory.

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

unsigned int  *disk_reg = (unsigned int *) disk_register_memory;

/* If disk error occured * *

disk_error_occured = (Disk_reg & 0x40000000) >> 31;

Exercise 12507

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

Exercise 12514

Write a function setbits (x,p,n,y) that returns x and the n bits that begin at position p set to the rightmost n bits of a n 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 bit S of y (a) and put them in X on position 10xxx010 to get answer 10111010.

The Your answer should print out of the result in binary form (the "can be" in the, Exercise, 12.1, and decimal form.

Your output should is 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 a unsigned char x and stores answer in Y.

The Your answer should print out of the result in binary form (the "can be" in the, Exercise, 12.1, and decimal form.

Your output should is like this:

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

Exercise 12516

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

The Your answer should print out of the result in binary form (the "can be" in the, Exercise, 12.1, and decimal form.

Your output should is like this:

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

Note: The functions developed should is as concise as possible 2. Original: Http://msdn.microsoft.com/en-us/library/ewwyfdbe (v=vs.71). aspx

Classes and structures can contain members that occupy less storage than a 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 ' is ' accessed in ' program. It must be a integral type (including enumerated types). The constant-expressionspecifies the number of bits, occupies in the structure. The Anonymous bit fields-that is, the Bit-field members with no identifier-can being used for padding.    Note An unnamed bit field of width 0 forces alignment of the "next bit field to" next type boundary, where type is the type of the member.

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

Bit_fields1.cpp
struct 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 the ' an object of type ' is shown in the following figure.

Memory Layout of Date Object

Note This 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 so 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 the data declared as bit fields is a from-to-high bit, as shown in the figure above.

End Microsoft specific

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

Bit_fields2.cpp
struct 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 is a integral type, as described in fundamental Types.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.