Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Carter P.A.PC assembly language.2005.pdf
Скачиваний:
15
Добавлен:
23.08.2013
Размер:
1.07 Mб
Скачать

56

CHAPTER 3. BIT OPERATIONS

3.4Manipulating bits in C

3.4.1The bitwise operators of C

Unlike some high-level languages, C does provide operators for bitwise operations. The AND operation is represented by the binary & operator1.

The OR operation is represented by the binary | operator. The XOR operation is represetned by the binary ^ operator. And the NOT operation is represented by the unary ~ operator.

The shift operations are performed by C’s << and >> binary operators. The << operator performs left shifts and the >> operator performs right shifts. These operators take two operands. The left operand is the value to shift and the right operand is the number of bits to shift by. If the value to shift is an unsigned type, a logical shift is made. If the value is a signed type (like int), then an arithmetic shift is used. Below is some example C

 

code using these operators:

 

1

short int s ;

/ assume that short int

is 16−bit /

2

short unsigned u;

/ s = 0xFFFF (2’s complement) /

3

s = −1;

4

u = 100;

/ u = 0x0064 /

 

5

u = u | 0x0100;

/ u = 0x0164 /

 

6

s = s & 0xFFF0;

/ s = 0xFFF0 /

 

7

s = s ˆ u;

/ s = 0xFE94 /

 

8

u = u << 3;

/ u = 0x0B20 (logical shift ) /

9

s = s >> 2;

/ s = 0xFFA5 (arithmetic

shift ) /

3.4.2Using bitwise operators in C

The bitwise operators are used in C for the same purposes as they are used in assembly language. They allow one to manipulate individual bits of data and can be used for fast multiplication and division. In fact, a smart C compiler will use a shift for a multiplication like, x *= 2, automatically.

Many operating system API2’s (such as POSIX 3 and Win32) contain functions which use operands that have data encoded as bits. For example, POSIX systems maintain file permissions for three di erent types of users: user (a better name would be owner), group and others. Each type of user can be granted permission to read, write and/or execute a file. To change the permissions of a file requires the C programmer to manipulate individual bits. POSIX defines several macros to help (see Table 3.6). The

1This operator is di erent from the binary && and unary & operators! 2Application Programming Interface

3stands for Portable Operating System Interface for Computer Environments. A standard developed by the IEEE based on UNIX.

Соседние файлы в предмете Электротехника