The bit field (bit segment) of the C struct, and the c struct

Source: Internet
Author: User
Tags domain list

The bit field (bit segment) of the C struct, and the c struct

When storing some information, it does not need to occupy a full byte, but only needs to occupy a few or one binary bit. For example, when storing a switch value, there are only two States: 0 and 1. Use one binary digit. To save storage space and simplify processing, the C language also provides a data structure called "bit domain" or "bit segment ". The so-called "bit field" refers to dividing the binary character in a byte into several different regions and showing the digits of each region. Each domain has a domain name, which allows operations by domain name in the program. In this way, several different objects can be represented by a byte binary field.
1. Definitions of bit domains and descriptions of bit domain Variables

The bit domain definition is similar to the structure definition in the form:

Struct bit domain structure name {bit domain list };

The list of bit domains is as follows:

Type description Character Domain Name: Bit domain Length

The description of bitfield variables is the same as that of structure variables. You can first define and then describe, and define or directly describe these three methods. For example:

struct bs{  int a:8;  int b:2;  int c:6;}data; 

It indicates that data is a bs variable, which occupies two bytes in total. Where a occupies 8 places, B occupies 2 places, and c occupies 6 places. The definitions of bit domains are described as follows:

1.One single-byte domain must be stored in the same byte and cannot be stored across two bytes.. If the remaining space of one byte is insufficient to store another domain, it should be stored from the next unit. You can also intentionally start a domain from the next unit. For example:

Struct bs {unsigned a: 4 unsigned B: 5/* starting from the next unit */unsigned c: 4}

2. Because bit fields cannot span two bytesThe length of a bit field cannot exceed the length of one byte..

3.Bit domain can have no bit Domain NameIn this case, it is only used for filling or adjusting the position. An anonymous domain cannot be used. For example:

Struct k {int a: 1 int: 2/* No-bit domain name, the 2-bit cannot use */int B: 3 int c: 2 };

Ii. Use of bit Domains

The following is an example of a company (white-collar technology-Qingdao) that encountered a written test. At that time, I did something wrong. To be afraid of forgetting it, please write it down.

#include <iostream>#include <memory.h>using namespace std;struct A{    int a:5;    int b:3;};int main(void){    char str[100] = "0134324324afsadfsdlfjlsdjfl";        struct A d;    memcpy(&d, str, sizeof(A));    cout << d.a << endl;    cout << d.b << endl;    return 0;}

Output on 32-bit x86 machine:

$ ./langxun.exe-161

Resolution: by default, to facilitate access and management of elements in the structure body, when the length of elements in the Structure Body is smaller than the number of digits of the processor, the longest element in the struct is the unit, that is, the length of the struct must be an integer multiple of the longest data element. If the Memory Length of the struct is greater than the number of processor digits, the Unit is aligned with the number of digits of the processor. Because it is a 32-bit processor and the element types A and B in the struct are both int (also 4 bytes), the memory occupied by the struct a is 4 bytes.

In the preceding example, the bit domain structure A is defined. The two bit domains are a (5 digits) and B (3 digits ), therefore, a and B occupy A single byte of structure a (A low byte ).

When the program runs to 14 rows, the d memory is allocated:

High 00110100 00110011 00110001 00110000 low position '4' '3' '1' '0' where d. a and d. B occupies one low byte (00110000) of d. a: 10000, d. b: 001

In d. a, the binary value is 10000 in the memory. Because d. a is a signed integer variable, it must be extended during output, so the result is-16 (the binary value is 11111111111111111111111111110000)

In the memory of d. B, the binary value is 001. Because d. B is a signed integer variable, it must be extended during output, so the result is 1 (the binary value is 00000000000000000000000000000001)

 3. Bit domain alignment

If the struct contains bit-field, the guidelines in VC are:

1) if the types of adjacent fields are the same, and the sum of the bit widths is smaller than the sizeof size of the type, the subsequent fields will be stored next to the previous field until they cannot be accommodated;

2) If the Field Types of adjacent bit fields are the same, but the sum of Bit Width is greater than the sizeof size of the type, the subsequent fields start from the new storage unit, its offset is an integer multiple of its type;

3) if the types of adjacent bitfield fields are different, the specific implementation of each compiler varies, VC6 adopts the non-compression mode (the fields of different bit domains are stored in different bit domain type bytes), and both Dev-C ++ and GCC adopt the compression mode;

The system first allocates space and padding for the struct members according to the alignment, and then performs bitfield operations on the variables.

 

I wrote a simple code and tested it myself,

 

# Include "stdafx. h "struct detail {int a: 1; int B: 2; int c: 5;} data1; struct ch2 {char a: 8; unsigned char B: 7; char c: 6; char d: 3; char e: 2; unsigned char f: 1; int g;} data2; // The NLE field occupies 12 bytes, struct ch3 {char a; char B; char c; char d; char e; char f; int g;} data3; int main (int argc, char * argv []) {data2.f = 0x3; data2. B = 0xff; printf ("Hello World! \ N "); printf (" size of data1 = % d data2 = % d data3 = % d \ n ", sizeof (data1), sizeof (data2 ), sizeof (data3); printf ("data2.f = % x, data2. B = % x \ n", data2.f, data2. B); return 0 ;}

 

Print the result,

Hello World!size of data1=4 data2=8 data3=12data2.f=1,data2.b=7f

 

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.