150 likes | 173 Views
Explore how bitwise operators manipulate bits in integral operands, from bytes to words. Learn shortcuts and practical applications with code examples.
E N D
Bitwise OperatorsFall 2008 Dr. David A. Gaitros dgaitros@admin.fsu.edu
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 • 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 <iostream> #include <iomanip> 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: 00011010 11101011 y: 00101100 00110110
Bitwise Operators // Logical AND operator x: 00011010 11101011 y: 00101100 00110110 -------------------- 00001000 00100010
Bitwise Operators // Logical OR operator x: 00011010 11101011 y: 00101100 00110110 ----------------- 00111110 11111111
Bitwise Operators // Logical XOR // (exclusive OR) x: 00011010 11101011 y: 00101100 00110110 ------------------- 00110110 11011101
Bitwise Operators // Shift Left 2 x: 00011010 11101011 ------------------------ 01101011 10101100 // Shift right 4 y: 00101100 00110110 ----------------- 00000010 11000011
Bitwise Operators // And here is the // complement of x (~x) x: 00011010 11101011 ------------------ ~x: 11100101 00010100
Bitwise Operators // So.. How do I set // a bit? void SetBit(int num) { int mask=1<<num; flags = flags | mask; }