䊐 Left and Right ShiftThe shift operators 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 re
Trang 1䊐 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,0bits 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 2n Shift-ing a number n places left (or right) is equivalent to a multiplication (or division) by 2n
Examples: unsigned res,number = 5;
res = number << 3; // 5 * 23 = 40
res = number >> 1; // 5 / 21 = 2
Trang 2710 C H A P T E R 3 1 M A N I P U L A T I N G B I T S
Bit pattern Bit position
higher bits lower bits
1 0 1 0 1
0 1 • • • •
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 positions
Example
#define MASK 0x20 char c = 'A';
c = c | MASK;
Trang 3䊐 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 0x7Fthe 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 ccan be of any integral type If the variable occupies more than one byte, the significant bits in the mask, 0x7F, are padded with 0bits 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 1and 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 0xAAis 10101010 Every second bit in the least significant eight bits of cis 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) ^ MASKrestores the value x The following overview demonstrates the effect of a statement for an integral expres-sionxand 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
Trang 4712 C H A P T E R 3 1 M A N I P U L A T I N G B I T S
// 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);
}
Computing the parity of an integer
Trang 5䊐 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 0and1are set The mask ∼3therefore 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 ∼3is 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)wherenis 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
Trang 6714 C H A P T E R 3 1 M A N I P U L A T I N G B I T S
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
Trang 7C++ 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 inttype
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_4designates the 5least significant bits in a computer word and can store values in the range 0to 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 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 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 48byte data section
or payload The header shown here is used to connect a computer to the network in the
User Network Interface.
Trang 8716 C H A P T E R 3 1 M A N I P U L A T I N G B I T S
****** 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)?
Sample screen output for exercise 1
Trang 9Exercise 1
a Write the function putBits()that outputs the bit pattern of a number
as an unsigned inttype 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-ablesxandy.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 xa 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 intvalue.The intvalue and the positions of the bits to be swapped are passed as argu-ments to the function.The return value is the new intvalue If one of the positions passed to the function is invalid, the intvalue 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
Trang 10718 C H A P T E R 3 1 M A N I P U L A T I N G B I T S
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;