80 likes | 255 Views
C Bit Manipulations. Bitwise Operators Logical Operators Displaying Bits Example Bitwise Assignment Operators. Bitwise Operators. Instructions are applied to each bit A & B bitwise AND Set to 1 if both bits are 1, otherwise 0 A | B bitwise inclusive OR
E N D
C Bit Manipulations • Bitwise Operators • Logical Operators • Displaying Bits Example • Bitwise Assignment Operators
Bitwise Operators • Instructions are applied to each bit • A & B bitwise AND • Set to 1 if both bits are 1, otherwise 0 • A | B bitwise inclusive OR • Set to 1 if at least one bit is 1, otherwise 0 • A ^ B bitwise exclusive OR • Set to one if only 1 bit is set to 1, otherwise 0 • ~ A one’s complement • All 1’s become 0’s & all 0’s become 1’s • See fig10_09.c in D & D textbook for examples (link on class webpage)
Logical Operators • Bitwise & logical operators are different • Logical operators operate on the variable as a whole (not on each bit) • Logical AND: && • Returns 1 if both variables are not 0, otherwise 0 • Logical OR: || • Returns 1 if at least 1 variable is not 0, otherwise 0 • Logical NOT:! • If variable is not 0, returns 0 • If variables is 0, returns 1
Bitwise Operators • A << B left shift • Shift the bits in A to the left B times • Fill in 0’s from the right • Same as multiplying by a power of 2 • A >> B right shift • Shift the bits in A to the right B times • Fill in 0’s for unsigned, 0’s for positive signed, and 1’s for negative signed • Same as diving by a power of 2 • See fig10_13.c in D & D textbook for examples (link on class webpage)
Displaying Bits • See fig10_07.c in D & D textbook (online version slightly altered) • Prints the binary representation of 32-bit unsigned integers • Uses the AND operator and a operand called a “mask” • Mask = an integer value with specific bits set to 1 • Used to hide some bits & select other bits • A zero (0) ANDed with anything produces zero (0) • A one (1) ANDed with anything produces itself
Assignment Operators x = x + 5; • Can also be written as x += 5; a *= b + 5; • Evaluates to a = a *(b + 5); • And not a = a * b + 5;
Bitwise Assignment Operators • A &= B bitwise AND assignment operator • Equivalent to A = A & B • A |= B bitwise OR assignment operator • Equivalent to A = A | B • A ^= B bitwise exclusive OR assignment operator • Equivalent to A = A ^ B • A <<= B left shift assignment operator • Equivalent to A = A << B • A >>= B right shift assignment operator • Equivalent to A = A >> B