Recitation - Mar 28, 2011
- A bit is the smallest unit of storage and represents either 1 or 0.
- Many conditions can be represented with a bit (e.g true/false, good/bad, on/off, etc.)
- Smallest unit of directly addressable memory is greater than a bit.
- C++ includes operators to provide bit manipulations.
- & (and)
- | (or)
- ^ (exclusive or)
- ~ (complement)
- << (shift left)
- >> (shift right)
- bitflags (example)
- Provide the ability to store an array of bits in the smallest storage space needed.
- Supports the following operations:
- Length() returns total number of bits allocated.
- Implementation should be portable to systems where character is > 8 bits.
- use sizeof operator to determine implementation's size of types. (e.g. sizeof(char))
- C++ guarantees about size of native types
- 1 = sizeof(char) ≤ sizeof(short) ≤ sizeof(int) ≤ sizeof(long)
- char is guaranteed to be at least 8 bits
- short and int at least 16 bits
- long at least 32 bits
- Handling of sign bit is typically machine dependent for some bitwise
operations. Therefore, it is a good idea to use unsigned types whenever
possible if bitwise operations are to be performed.
- sign extension - basically, fill additional upper bits with 0 if sign bit is 0,
otherwise if sign bit is 1, set additional upper bits with 1.
- Good idea to test program on more than one OS/architecture, since
your implementation should be machine independent.
Additional Notes