// MoreComplicated.c // // Jaylen VanOrden // CSE 351 TA // 9-27-2012 // // Gives example code for using bitwise and logical operators // as well as a function which uses printf and a bit mask to // print out decimal and binary representations of numbers. #include // This is a function prototype - it lets C know // what the parameters for the function will be. // We have to include this before we call the function. void displayTwice(const char* varName, int toDisp); int main (int argc, char* argv[]){ // Example variables int x = 5; int y = 103; displayTwice("x",x); displayTwice("y",y); // Bitwise operators int or_op = x | y; int and_op = x & y; int xor_op = x ^ y; displayTwice("x | y", or_op); displayTwice("x & y", and_op); displayTwice("X ^ y", xor_op); // Logical operators int logical_or = x || y; int logical_and = x && y; displayTwice("x || y", logical_or); displayTwice("x && y", logical_and); printf("\nJust working with x now...\n"); // Shift operators int shift_left = x << 2; int shift_right = x >> 1; displayTwice("x << 2", shift_left); displayTwice("x >> 1", shift_right); return 0; } /* * Prints out the variable name and its value in decimal and binary * form. * * Ex: * displayTwice("bob",9); * Prints: * bob: 9 00001001 */ void displayTwice(const char* varName, int toDisp){ // %s means "print this string" // %d means "display this as a decimal" // \t still means tab printf("%s:\t%d\t",varName,toDisp); int i; // Print each bit of the binary representation out // For each step, if the bit is set, print a 1 // otherwise, print a 0. for(i = 0; i < 8; i++){ // Arithmetic shift here? unsigned int mask = 0x80 >> i; unsigned int result = toDisp & mask; // Debug print: // printf("\nLooking at spot %d, got mask 0x%x, got result 0x%x / %u\n", i, mask, result, result); if(result > 0){ printf("1"); } else { printf("0"); } } // Print a newline character to keep things clean printf("\n"); }