CSC195, Class 14: Fun with Bitwise Operations Overview: * Summary of bitwise operations * Using bitwise operations * Lab Notes: * No homework (yet) so that you have time to finish the labs. * Read K&R 6.1, 6.7-6.9 * CS195/201 passed the division. It's on to the curriculum committee. * Snacks. Sam is easy to manipulate. * Any questions on yesterday's work? ---------------------------------------- C provides a host of operations on integers that reflect the underlying bit representation of those integers * & * | * ~ * ^ * << * >> ---------------------------------------- Why would a programming language provide these operations? * Reminds you that the language is low-level. * You might want to do "funky low-level manipulations" * Efficiently interact directly with .... other hardware. * We could apply Gries-style logic to everything! Yay! * "Smart" programmers can choose appropriate operations. + Divide by 4: Shift right two bits. + Multiply by 8: Shift left three bits. * Efficient storage of sets of Boolean values (and other small values) * E.g. permissions: b b b b b b b b b r w x r w x r w x u u u g g g o o o We can use the bitwise operations to combine settings: Writeable by other: 2 Readable by group is 32 Writable by other and readable by group: | Good C programmers, trying to be efficient, often define a set of constants that can be logically combined. #define WRITEABLE 02 #define READABLE 04 #define EXECUTABLE 01 myprog = WRITABLE | EXECUTABLE ---------------------------------------- REFLECTIONS * Integer values that start with 0 are octal + Octal 07: Binary 111 + Octal 06: Binary 110 + Octal 070: Binary 111000 * Integer values that start with 0x are hexidecimal * Example of potentially good testing * How to write "printbits"