C language uses structure to implement bit segments

Source: Internet
Author: User
Tags ack

Use the structure in C language to implement bitwise segments-personal efforts! It's worth watching! The structure in C language has the ability to implement bit segments. Oh! You asked what form it is, right? You will be given an answer to this question. Let's take a look at the role of the bit segment: the bit segment is implemented by adding a colon and an integer representing the bit length after the field declaration. This usage is also called "Deep programming of logical components". If you are interested in system programming, you should not miss this article!
I will tell you the reasons for using a bit segment: 1. It can wrap data with an odd number in length to save storage space; 2. It can easily access part of an integer value.
First of all, I would like to remind you that: 1. There are only three types of bit segments: int, unsigned int, and signed int (of course, I have no idea whether the int bit segment can take negative numbers, because it is determined by your compiler. Bit, bit, which is used to represent the bit length of a field. It only has an integer value and does not have the float type 7.2. If you say yes, then you acknowledge the concept of 7.2 people, and of course there is no char type); 2. A colon and an integer after the member name, this integer specifies the length of the bit segment (BIT); 3. Many compilers limit the length of the bit segment member to the length range of an int; 4. the compiler determines whether the implementation of a bit segment member in the memory is from left to right or from right to left, but both are right.
Next let's take a look at what it is (I assume that the length of the machine is 32 characters ):
Struct word
{
Unsigned int chara: 6:
Unsigned int Font: 7;
Unsigned int maxsize: 19;
};
Struct word Chone;
This section is taken from a Text Formatting software I have compiled. It can accommodate up to 64 characters (that is, the unsigned int chara: 6 Characters in total) different character values, can process 128 (both unsigned int Font: 7; both 2 to the power of 7) Different fonts, and 2 to the power of 19 characters in length. We can see that maxsize is 19 BITs and cannot be accommodated by a short int type value. We can also see that the length of the remaining Members is smaller than that of char, this reminds us of sharing the 32-bit machine font length, which avoids the use of a 32-bit integer to represent the maxsize bit segment. How is it? Note that the Code just now cannot be implemented on a 16-character long machine. Why? Let me remind you to see the above 3rd points, you will understand!
Did you find this thing useless? If you nod, you are wrong! How can such a great creation be useless? (You are not interested in system programming. I believe you will change this point of view )? Do you know the disk controller? The communication between the floppy disk and its controller is as follows:
│ Reject 5 → │ reject 5 → │ reject 9 → │ reject 8 → │ reject 1 → │ reject 1 → reject 1 → reject 1 → reject 1 → reject 1 → reject
The meaning of the above bit segments from left to right is: 5-bit command, 5-bit sector, 9-bit track, 8-bit error code, 1-Bit Head loaded, 1-bit write protection, 1-bit disk spinning, 1-Bit Error identifier, and 1-bit ready. How can it be implemented? First, you can write and read:
Struct disk_format
{
Unsigned int command: 5;
Unsigned sector: 5;
Unsigned track: 9;
Unsigned err_code: 8;
Unsigned ishead_loaded: 1;
Unsigned iswrit_protect: 1;
Unsigned isdisk_spinning: 1;
Unsigned iserr_ocur: 1;
Undigned isready: 1;
};
Note: In the Code, except for the first line, the unsigned int is used to declare the bit segment, which saves Int. This is feasible. For details, see the anci c standard.
If we want to access the 044c18bfh address, it will be like this:
# Define disk (struct disk_format *) 0x044c18bf)
Disk-> sector = fst_sector;
Disk-> track = fst_track;
Disk-> command = write;
Of course, those are all macro-defined!
It is very convenient for us to use bit segments to achieve this purpose. In fact, this can also be achieved through shift or blocking. You will know which one is more convenient after you try it!
Our topic today is here. If you have any questions, please email me: arhuwen@163.com;
Special statement: Do not use the above content for illegal behaviors. Otherwise, you will be responsible for the consequences. In addition, this article cannot be used for any action to seek commercial benefits!

 

C compiler allocates the default structure space
In the C language, the structure is a composite data type, and its components can be both variables of basic data types (such as int, long, float, and so on, it can also be a data unit of a composite data type (such as array, structure, union, and so on. In the structure, the compiler allocates space for each member of the structure based on its natural alignment condition. Each member is stored in the memory in the order they are declared, the address of the first member is the same as the address of the entire structure. By default, the C compiler allocates space for each variable or data unit based on its natural limitations. See table 1:


Table 1: Natural bounded conditions under Win32
For example, the following structure shows the allocation of member spaces:
Struct test {
Char x1;
Short X2;
Float X3;
Char X4;
};
  
Figure 1: Default structure space allocation
The first member of the structure X1, whose offset address is 0, occupies 1st bytes. The second member X2 is of the short type, and its starting address must be two byte pairs. Therefore, the compiler fills a Null Byte between X2 and X1. The third member X3 and fourth member X4 of the structure exactly fall on their natural peer address, and no additional bytes are needed before them. In the test structure, the X3 member requires a 4-byte bounded boundary and is the maximum boundary unit required by all the members of the structure. Therefore, the natural boundary condition of the test structure is 4 bytes, the compiler fills in three NULL bytes after Member X4. The entire structure occupies 12 bytes of space.

Bits in the Structure
The so-called bitwise segment is a member of the struct type that defines the length in units of bits. The compiler follows the following principles for allocating the structure median:
? For a bit segment with a length of 0, the next bit segment is stored from the next storage unit:
For example:
Struct t {
Unsigned char A: 1;
Unsigned char B: 2;
Unsigned: 0;
Unsigned C: 3;
};
The members a and B of structure T are in one storage unit, while C is in another storage unit.
? A single segment must be stored in the same storage unit and cannot be stored across two units:
For example:
Struct t {
Unsigned char A: 4;
Unsigned char B: 6;
};
The member A of structure T is in one storage unit, and B is in another storage unit.

Change the default Allocation Policy of the C Compiler
Generally, you can use the following two methods to change the default peer condition:
? Use pseudoinstructions # pragma pack ([N])
? Use command line parameters during compilation
# Pragma pack ([N]) pseudoinstructions allow you to select the peer policy adopted by the compiler to allocate space for data, as shown in table 2:


Table 2: Change the default peer Condition
In microsfot visual c ++, the command line parameter/ZP [N] can change the default peer condition. In Borland C ++ builder, the command line parameter-A [n] can change the default peer condition. The meaning of N is the same as that in # pragma pack.
For example, after the # pragma pack (1) Directive is used, the space allocation of each member in the test structure is shown in Figure 2:
  

Figure 2: structure space allocation after # pragma pack (1)

Application Instance

In our daily programming work, especially the processing of some network transactions, we often have various protocols with others: for example, the header I sent to you in 20 bytes, the first four bytes represent ...... And so on. Many people get various information through the pointer offset method. This method is not only complicated in programming, but also troublesome to modify the program once the Protocol changes. After learning about the compiler's allocation principles for the structure space, we can use this feature to define our own protocol structure and obtain various information by accessing the structure members. In this way, not only programming is simplified, but even if the protocol changes, we only need to modify the definition of the protocol structure. Other programs do not need to be modified, saving time and effort. The following uses the TCP protocol header as an example to describe how to define the protocol structure.
TCP protocol header 3:
  

Figure 3: TCP Header
The protocol structure is defined as follows:
Struct tcpheader {
Short srcport; // 16-bit source port number
Short dstport; // 16-bit destination port number
Int serialno; // 32-bit serial number
Int ackno; // 32-bit confirmation number
Unsigned char haderlen: 4; // 4-bit Header Length
Unsigned char reserved1: 4; // retain four of the six digits
Unsigned char reserved2: 2; // retain two of the six digits
Unsigned char URG: 1;
Unsigned char ack: 1;
Unsigned char PSH: 1;
Unsigned char rst: 1;
Unsigned char SYN: 1;
Unsigned char Fin: 1;
Short windowsize; // 16-bit window size
Short tcpchksum; // 16-bit TCP check
Short urgentpointer; // 16-bit emergency pointer
};
The protocol structure can also be defined as follows:
Struct tcpheader {
Short srcport; // 16-bit source port number
Short dstport; // 16-bit destination port number
Int serialno; // 32-bit serial number
Int ackno; // 32-bit confirmation number
Unsigned char haderlen: 4; // 4-bit Header Length
Unsigned char: 0; // retain four of the six digits
Unsigned char Reserved: 2; // retain 2 of the 6 digits
Unsigned char URG: 1;
Unsigned char ack: 1;
Unsigned char PSH: 1;
Unsigned char rst: 1;
Unsigned char SYN: 1;
Unsigned char Fin: 1;
Short windowsize; // 16-bit window size
Short tcpchksum; // 16-bit TCP check
Short urgentpointer; // 16-bit emergency pointer

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.