Bitwise Operators and Shifts

// done by zephinzer // goto: http://zephinzer.tumblr.com for more // please leave this intact if you use this code // thank you #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> // control the program from here #define VALUE_OF_X 532 // this is for bitwise operators section #define VALUE_OF_Z 315 // this is for bitwise operators section #define VALUE_OF_2X 4 // this is for bitwise shift section // control the program from here void binary(int, char []); int main(void) { int count, x = VALUE_OF_X, z = VALUE_OF_Z; char output[16]; printf("\nbitwise.c by zephinzer"); printf("\n^^^^^^^^^^^^^^^^^^^^^^\n"); printf("The |, &, ^ and ~ bitwise operators:\n"); printf("x=%d; z=%d;\n", x, z); printf("x|z = %d\n", x|z); binary(x, output); printf("x = %s = %d\n", output, x); binary(z, output); printf("z = %s = %d\n", output, z); binary(x|z, output); printf("x|z = %s = %d\n\n", output, x|z); printf("x&z: %d\n", x&z); binary(x, output); printf("x = %s = %d\n", output, x); binary(z, output); printf("z = %s = %d\n", output, z); binary(x&z, output); printf("x|z = %s = %d\n\n", output, x&z); printf("x^z: %d\n", x^z); binary(x, output); printf("x = %s = %d\n", output, x); binary(z, output); printf("z = %s = %d\n", output, z); binary(x&z, output); printf("x|z = %s = %d\n\n", output, x^z); printf(" x: %d\t\tz: %d\n", x, z); printf("~x: %d\t~z: %d\n", ~x, ~z); putch('\n'); printf("The bitwise shift << >> operators:\n"); x = VALUE_OF_2X; printf("x = %d\n", x); for(count=1; count<10; count++) { binary(x<<count, output); printf("x<<=%d; %d \t%s\n", count, x<<count, output); } binary((x <<= (count-1)), output); printf("x = %d \t%s\n", x, output); for(count=1; count<10; count++) { binary(x>>count, output); printf("x>>%d: %d \t%s\n", count, x>>count, output); } printf("Press any key to continue..."); getch(); putch('\n'); return 0; } void binary(int num, char output[]) { itoa(num, output, 2); int len = strlen(output); memmove(&output[15-len], output, len); int count; for(count = 0; count < 15-len; count++) output[count] = '0'; output[15] = '\0'; }
Educational program for showing how bitwise functions work
Content includes:
Effects of &, |, ^ and ~
Effects of << and >>

~ zephinzer
- http://zephinzer.tumblr.com

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.