CIS 29 - Notes for Thursday, 1/28

Announcements and Reminders


Recording

I/O Manipulators

The std manipulators

Write your own manipulator



Data at the Bit Level

Example 8-1 – Primitive data at the bit level

Example 8-2 – Non-primitive data at the bit level

Bitwise Operators

& operator

The bitwise and operator returns a 1 only when both bits being compared are 1.  For example:

10101110 & 00101010   => 00101010

| operator

The bitwise or operator returns a 1 only when either bits being compared are 1.  For example:

10101110 | 00101010    => 10101110

^ operator

The bitwise exclusive or operator returns a 1 only when either, but not both, bits being compared are 1.  For example:

10101110 | 00101010    => 10000100

~ operator

The bitwise not, or complement operator is a unary bitwise operator.  It returns a 1 when the bit is 0 and returns a 0 when the bit is 1.  For example:

~10101110    => 01010001

<< operator

The bitwise left-shift operator shifts bits to left the number of positions as the right-hand operand.  Bits on the right are filled with zeros.  Bits on the left are lost.  The left-shift operator may be used to perform multiplication by integer powers of two.  For example,

10101110 << 2   => …10 10111000

>> operator

The bitwise right-shift operator shifts bits to right the number of positions as the right-hand operand.  Bits on the left are filled with zeros.  Bits on the right are lost.  The left-shift operator may be used to perform division by integer powers of two.  For example,

10101110 >> 2   => 00101011 10…

The bitwise assignment operators

The bitwise assignment operators:  &=, |=, ^=, <<=, and >>= perform the implied operation and assign the resultant value to the left-hand argument.

Example 8-3 – Bitwise operators

Bitwise Techniques

Turn a bit on

Use the or assignment bitwise operator to turn a bit on.  If the bit is already turned on, the operation has no effect.

Integer_value |= bit

Turn a bit off

Use the and assignment with the not bitwise operators to turn a bit off.  If the bit is already turned on, the operation has no effect.

Integer_value &= ~bit

Toggle a bit

Use the exclusive or assignment operator to turn a bit off. 

Integer_value  ^= bit

Test a bit

Use the and operator to see if a bit is turned on. 

Integer_value  & bit

Example 8-4 – Bitwise operator techniques