Bitwise Operators Fall 2008 Dr. David A. Gaitros
Bitwise Operators “Mathematics may be the language of scientists, but binary is the language of Computer Scientists” Dr. David A. Gaitros
Binary Operations Recall the following: – A bit is the smallest digit capable of being stored in a modern day digital computer. – A byte, consisting of 8 bits is the smallest unit of storage that a computer can work with. – A word ( usually somewhere between 32 and 64 bits) is the smallest addressable item in a computer. The word size of a computer is usually dictated by either the bus size of the system or the word size of the CPU.
Bitwise Operators OperatorNameDescription & bitwise AND1 only if both operands are 1. |bitwise OR1 if ether or both operands are 1 ^bitwise exclusive or1 if either but not both operands are 1 <<Left ShiftShifts bits of the first operand by the number of bits specified by the second operand. >>Right ShiftShifts bits of the first operand by the number of bits specified by the second operand. ~ComplementFlips the bits in the operand. All 1’s become 0’s and all 0’s become 1’s.
Bitwise Operators Bitwise operators are used to directly manipulate the bits of integral operands such as char, short, int, long (both signed and unsined). Normally unsigned integers are used when dealing with bitwise operations.
Bitwise Operations Code Example: #include using namespace std; int main(void) { unsigned x=10; unsigned y=0; y = x | y; return 0; } // What does this do? // Nothing really.
Bitwise Operators Shortcuts X &= y; same as x = x & y; x |= y; same as x = x | y; x ^= y; same as x = x ^ y; x << y; same as x = x << y; x >> y; same as x = x>> y;
Bitwise Operations Why use them? – A single bit shift left is a very fast way of integer multiplication by 2. – A single bit shift right is a very fact way of integer division by 2. – An AND operation with all zeros is a very efficient way to clear out a field. – We can use single bits in a word (32 bits) to represent Boolean values very efficiently. These are sometimes call flags.
Bitwise Operators short x = 6891; short y = 11318; Internal Representation x: y:
Bitwise Operators // Logical AND operator x: y:
Bitwise Operators // Logical OR operator x: y:
Bitwise Operators // Logical XOR // (exclusive OR) x: y:
Bitwise Operators // Shift Left 2 x: // Shift right 4 y:
Bitwise Operators // And here is the // complement of x (~x) x: ~x:
Bitwise Operators // So.. How do I set // a bit? void SetBit(int num) { int mask=1<<num; flags = flags | mask; }