A Complete Guide to Programming in C++ part 74 ppt

10 303 0
A Complete Guide to Programming in C++ part 74 ppt

Đang tải... (xem toàn văn)

Thông tin tài liệu

BITWISE SHIFT OPERATORS ■ 709 ᮀ Left and Right Shift The shift operators << and >> shift the bit pattern of their left operand a certain number of bit positions. The number of positions is defined by the right operand. The examples opposite illustrate this point. In the case of a left shift, 0 bits are padded. The bits dropped on the left are lost. Example: short x = 0xFF00; x = x << 4; // Result: 0xF000 In the case of a right shift, 0 bits are padded from the left if the left operand is an unsigned type or has a positive value. In all other cases, the compiler determines whether to pad an expression with 0 bits (logical shift) or with the sign bit (arithmetic shift), although an arithmetic shift normally occurs. Example: short x = 0xFF00; x = x >> 4; // Result: 0xFFF0 To ensure portable source code, you should use right shifts for positive values only. ᮀ Integral Promotion Integral promotion is performed for the operands of a shift operator, that is char is extended to int. The result type in a shift operation is then the same as the type of the left operand after integral promotion. The result of a shift operation is unpredictable if the value of the right operand is neg- ative or larger than the length of the left operand expressed in bits. Example: char x = 0xFF; x = x >> 9; // undefined result ᮀ Applications Shift operators allow you to perform efficient multiplication and division with 2 n . Shift- ing a number n places left (or right) is equivalent to a multiplication (or division) by 2 n . Examples: unsigned res,number = 5; res = number << 3; // 5 * 2 3 = 40 res = number >> 1; // 5 / 2 1 = 2 710 ■ CHAPTER 31 MANIPULATING BITS Bit pattern Bit position higher bits lower bits n n-1 4 3 2 1 0 1010101 •••• Current bit patterns: 0 1 0 0 0 0 0 1 'A' = 0x41 | 0 0 1 0 0 0 0 0 MASK = 0x20 0 1 1 0 0 0 0 1 'a' = 0x61 ■ BIT MASKS Bit positions Example #define MASK 0x20 char c = 'A'; c = c | MASK; BIT MASKS ■ 711 ᮀ Deleting Bits The bitwise AND operator is normally used to delete specific bits. A so-called mask is used to determine which bits to delete. Example: c = c & 0x7F; In the mask 0x7F the seven least significant bits are set to 1, and all significant bits are set to 0. This means that all the bits in c, with the exception of the least significant bits, are deleted. These bits are left unchanged. The variable c can be of any integral type. If the variable occupies more than one byte, the significant bits in the mask, 0x7F, are padded with 0 bits when integral promo- tion is performed. ᮀ Setting and Inverting Bits You can use the bitwise OR operator | to set specific bits. The example on the opposite page shows how to change the case of a letter. In ASCII code, the only difference between a lowercase and an uppercase letter is the fifth bit. Finally, you can use the bitwise exclusive OR operator ^ to invert specific bits. Each 0-bit is set to 1 and each 1-bit is deleted if the corresponding bit in the mask has a value of 1. Example: c = c ^ 0xAA; The bit pattern for 0xAA is 10101010. Every second bit in the least significant eight bits of c is therefore inverted. It is worthy of note that you can perform double inversion using the same mask to restore the original bit pattern, that is, (x ^ MASK) ^ MASK restores the value x. The following overview demonstrates the effect of a statement for an integral expres- sion x and any given mask, MASK: ■ x & MASK deletes all bits that have a value of 0 in MASK ■ x | MASK sets all bits that have a value of 1 in MASK ■ x ^ MASK inverts all bits that have a value of 0 in MASK. The other bits are left unchanged. 712 ■ CHAPTER 31 MANIPULATING BITS // parity_t.cpp: Defines the function parity(), which // computes the parity of an unsigned // value. // Returns: 0, if the number of 1-bits is even, // 1 in all other cases. // inline unsigned int bit0( unsigned int x ) { return (x & 1); } int parity( unsigned int n) { unsigned int par = 0; for( ; n != 0; n >>=1 ) par ^= bit0(n); return (par); } ■ USING BIT MASKS Computing the parity of an integer USING BIT MASKS ■ 713 ᮀ Creating Your Own Masks You can use the bitwise operators to create your own bit masks. Example: x = x & ∼3; In the bit pattern of 3, only the bits at positions 0 and 1 are set. The mask ∼3 therefore contains a whole bunch of 1-bits and only the two least significant bits are 0. The above expression would thus delete the two least significant bits in x. The mask ∼3 is independent of the word length of the computer and is thus preferable to the mask 0xFFFC. The next example shows masks that address exactly one bit in a word. They are cre- ated by left shifting 1. Examples: x = x | (1 << 6); x = x & ∼(1 << 6); The first expression sets the sixth bit in x. The same bit is then deleted, as only the sixth bit in the mask ∼(1 << 6) has a value of 0. Of course, you can also use masks such as (1 << n) where n is a variable containing the bit position. Example: int setBit(int x, unsigned int n) { if( n < sizeof(int) ) return( x & (1 << n); } ᮀ Bitwise Operators in Compound Assignments The binary bitwise operators &, |, ^, <<, and >> can be used in compound assignments. Examples: x >>= 1; x ^= 1; Both statements are equivalent to x = x >> 1; x = x ^ 1 The function parity() shown opposite includes compound assignments with bitwise operators. Parity bit computation is used to perform error recognition in data communi- cations. 714 ■ CHAPTER 31 MANIPULATING BITS Byte General Flow Control Header Error Control Virtual Path Identifier Virtual Channel Identifier Virtual Channel Identifier Virtual Channel Identifier Payload Type CLP Virtual Path Identifier General Flow Control Virtual Path/Channel Identifier Payload Type Controls the data stream Address of the virtual path/channel Distinguish between payload and control data Mark cells with high priority Check sum for header CLP (Cell Loss Priority) Header Error Control 1 2 3 4 5 struct ATM_Cell { unsigned GFC : 4; // General Flow Control unsigned VPI : 8; // Virtual Path Identifier unsigned VCI : 16; // Virtual Channel Identifier unsigned PT : 3; // Payload Type unsigned CLP : 1 // Cell Loss Priority unsigned HEC : 8; // Header Error Control char payload[48]; // Payload }; ■ BIT-FIELDS Header of ATM cells Representing an ATM cell BIT-FIELDS ■ 715 C++ lets you divide a computer word into bit-fields and give the bit-fields a name. Bit- fields offer major advantages; their uncluttered structure makes them preferable and less error prone than using masks and bitwise operators to manipulate individual bits. ᮀ Defining Bit-Fields Bit-fields are defined as data members of a class. Each bit-field is of unsigned int type with an optional name and width. The width is defined as the number of bits the bit-field occupies in a computer word and is separated from the bit-field name by a colon. Example: struct { unsigned bit0_4 : 5; unsigned : 10; unsigned bit15 : 1; } word; The member word.bit0_4 designates the 5 least significant bits in a computer word and can store values in the range 0 to 31. The second data member does not have a name and is used to create a gap of 10 bits. The member word.bit15 contains the value at bit position 15. You cannot reference nameless bit-fields. They are used to align the subsequent bit- fields at specific bit positions. The width of a bit-field cannot be greater than that of the computer word. The width 0 has a special significance; the subsequent bit-field is positioned on the next word boundary, that is, it begins with the next computer word. If a bit-field will not fit in a computer word, the following bit-field is also positioned on the next word boundary. There are several special cases you need to consider when dealing with bit-fields: ■ you cannot use the address operator for bit-fields. You cannot create arrays of bit- fields. Neither restriction applies to a class containing bit-field members, how- ever. ■ the order bit-fields are positioned in depends on the machine being used. Some computer architectures position bit-fields in reverse order. This is true of DEC Alpha workstations, for example. ᮀ The Sample Program Opposite The opposite page shows a class designed to represent ATM cells. Cells are used for data transportation in ATM (Asynchronous Transfer Mode) networks. Each cell comprises a 5 byte header with addresses and a checksum for error checking and 48 byte data section or payload. The header shown here is used to connect a computer to the network in the User Network Interface. exercises 716 ■ CHAPTER 31 MANIPULATING BITS ****** BITWISE OPERATORS ****** Please enter two integers. 1st Number > 57 2nd Number > -3 The bit pattern of 57 = x : 0000 0000 0011 1001 The bit pattern of -3 = y : 1111 1111 1111 1101 The bit pattern of x & y : 0000 0000 0011 1001 The bit pattern of x | y : 1111 1111 1111 1101 The bit pattern of x ^ y : 1111 1111 1100 0100 How many bit positions is x to be shifted? Count > 4 The bit pattern of x << 4 : 0000 0011 1001 0000 The bit pattern of x >> 4 : 0000 0000 0000 0011 Repeat (y/n)? ■ EXERCISES Sample screen output for exercise 1 EXERCISES ■ 717 Exercise 1 a. Write the function putBits() that outputs the bit pattern of a number as an unsigned int type. Only the 16 least significant bits are to be output no matter what the size of the computer word.The number is passed as an argument to the function, which has no return value. b. Write a tutorial to demonstrate the effect of bitwise operators. First read two decimal integers from the keyboard and store them in the vari- ables x and y.Then use the function putBits() to output the bit pat- terns of x, x&y, x | y, x ^ y, and ∼x. To demonstrate the shift operators, shift the value of x a given number of bit positions right and left. Read the number of bit positions from key- board input. Use the value 1 in case of invalid input. The opposite page shows sample output from the program. Exercise 2 Your task is to encrypt data to prevent spying during data communications.The sender uses a filter to encrypt the data in question, and the receiver uses the same filter to decrypt the transmission. a. Define the function swapBits() that swaps two bits in an int value.The int value and the positions of the bits to be swapped are passed as argu- ments to the function.The return value is the new int value. If one of the positions passed to the function is invalid, the int value should be returned unchanged. b. Write a filter that swaps the bits at bit positions 5 and 6, 0 and 4, and 1 and 3 in all characters except control characters (defined as ASCII Code >= 32). Test the filter by writing the encrypted output to a file and then using the same filter to output the new file.The output must comprise the original unencrypted data. solutions 718 ■ CHAPTER 31 MANIPULATING BITS ■ SOLUTIONS Exercise 1 // // bits_t.cpp // Demonstrates bitwise operators. // #include <iostream> #include <iomanip> using namespace std; void putbits( unsigned int n); // Prototype of putbits() int main() // Learning bitwise operations { int x, y, count; char yn; do { cout << "\n\n ****** BITWISE OPERATIONS ******\n"; cout << "\nPlease enter two integers.\n\n" << "1st number > "; cin >> x; cout << "2nd number > "; cin >> y; cout << "\nThe bit pattern of " << setw(6) << x << " = x : "; putbits(x); cout << "\nThe bit pattern of " << setw(6) << y << " = y : "; putbits(y); cout << "\nThe bit pattern of x & y : "; putbits(x&y); cout << "\nThe bit pattern of x | y : "; putbits(x|y); cout << "\nThe bit pattern of x ^ y : "; putbits(x^y); cout << "\n\nHow many bit positions" " is x to be shifted?" << "\nNumber > "; cin >> count; . that have a value of 0 in MASK ■ x | MASK sets all bits that have a value of 1 in MASK ■ x ^ MASK inverts all bits that have a value of 0 in MASK. The other bits are left unchanged. 712 ■ CHAPTER. a name. Bit- fields offer major advantages; their uncluttered structure makes them preferable and less error prone than using masks and bitwise operators to manipulate individual bits. ᮀ Defining. designates the 5 least significant bits in a computer word and can store values in the range 0 to 31. The second data member does not have a name and is used to create a gap of 10 bits. The member

Ngày đăng: 06/07/2014, 17:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan