A Complete Guide to Programming in C++ part 74. This book provides both novice and experienced programmers with a comprehensive resource manual for the C++ programming language. Readers gain experience in all aspects of programming, from elementary language concepts to professional software development, with in depth coverage of all the language elements en route. These elements are carefully ordered to help the reader create useful programs every step of the way. | 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 oxffoo 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 oxffoo 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 negative or larger than the length of the left operand expressed in bits. Example char x oxff x x 9 undefined result Applications Shift operators allow you to perform efficient multiplication and division with 2n. Shifting 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 710 CHAPTER 3 I MANIPULATING BITS BIT MASKS Bit positions Example define MASK 0x20 char c A c c MASK 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 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 .