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:
Table: Bitwise operators
& |
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 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:
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.
This function illustrates many C program points:
-
for loop not used for simple counting operation
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.
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 (Figure12.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;
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.
-
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++
int bitcount(unsigned char x)
{int count;
for (count=0; x != 0; x>>=1)
if ( x & 01)
count++;
return count;
}
分享到:
相关推荐
英文题库C目录1. Data Types, Operators and Expressions 1 Variable Names – 1 1 Data Type
Lecture Notes in Mathematics Edited by A. Dold and B. Eckmann Applications to Partial Differential Equations
英文题库C目录1. Data Types, Operators and Expressions 1 Variable Names – 1 1 Data Type
C程序设计英文课件:CHAPTE 2 Types,Operators and Expressions
Low Level I/O - Read and Write Open, Creat, Close, Unlink Random Access - Lseek Example - An implementation of Fopen and Getc Example - Listing Directories Example - A Storage Allocator Appendix...
Teradata SQL Functions, Operators, Expressions, and Predicates
C程序设计英文课件:CHAPTE 2 Types,Operators and Expressions.ppt
This book is about low level bit programming Table of Contents Chapter 1. Given an unsigned int, swap the bits in odd and even positions Chapter 2. Print the binary representation of an unsigned int...
Why and how something happened. Furthermore, it may serve as a reference and guide for beginners who want to learn Banach space theory with some historical flavor. Helpful information is provided for ...
There are plenty of good books written on the subject, but I found no clear and concise set of rules on the Internet for those who don't want to understand every nuance of the language—and just want...
NULL 博文链接:https://thatsmyiteye.iteye.com/blog/541868
小波与算子 ,是小波领域权威书籍,适合研究小波的学者。
JSON Functions And Operators.md
CSharp - Module 12_Operators Delegates and Events
Schrodinger Operators With Application to Quantum Mechanics and Global Geometry (Theoretical and Mathematical Physics) by Hans L. Cycon, Richard G. Froese, Werner Kirsch, Barry Simon (z-lib.org).djvu
Evolutionary computation
按 照 运 算 符 功 能 来 分 ,将JAVA基 本 的 运 算 符 分类。
This textbook explains the concepts and techniques required to write programs that can handle large...Appendix E: Dictionary Operators and Methods Appendix F: Turtle Methods Appendix H: Complete Programs
中间过程、临界现象--分数阶算子理论、方法、进展,徐明瑜,谭文长,从物理学特别是力学的观点出发,简要介绍了用以描述物理和力学中的中间过程(intermediate processes)和临界现象(critical phenomena)的分�
Next, it examines the challenges operators and vendors are likely to face—explaining the critical role network planning and optimization play in addressing these challenges. The book details ...