diff --git a/algorithms/bit-manipulation/addition.c b/algorithms/bit-manipulation/addition.c new file mode 100644 index 00000000..5d6f65eb --- /dev/null +++ b/algorithms/bit-manipulation/addition.c @@ -0,0 +1,20 @@ +#include + +int add(int x, int y) +{ + while(x > 0) + { + unsigned int carry = x & y; + y = x ^ y; + x = carry << 1; + } + return y; +} + +int main() +{ + printf("sum of %d and %d is %d\n", 3, 4, add(3, 4)); + return 0; +} + + diff --git a/algorithms/bit-manipulation/check_power_of_2.c b/algorithms/bit-manipulation/check_power_of_2.c new file mode 100644 index 00000000..fd7baef3 --- /dev/null +++ b/algorithms/bit-manipulation/check_power_of_2.c @@ -0,0 +1,15 @@ +#include + +#define check_power_of_2(x) (!( x & (x - 1)) && (x > 1)) + +int main() +{ + for(int i = 1; i < 100; i++) + { + if(check_power_of_2(i)) + printf("True! %d is a power of 2\n", i); + else + printf("False! %d is not a power of 2\n", i); + } + printf("Hello World\n"); +} \ No newline at end of file diff --git a/algorithms/bit-manipulation/modulus_with_power_of_2.c b/algorithms/bit-manipulation/modulus_with_power_of_2.c new file mode 100644 index 00000000..a1346e4a --- /dev/null +++ b/algorithms/bit-manipulation/modulus_with_power_of_2.c @@ -0,0 +1,20 @@ +/* + 1. Here is an example of the modulus operation + using bit manipulation + 2. It is supposed to be much faster and more efficient + The only condition is that n should be a power of 2 +*/ + +#include + +#define modulo(x,n) ((x) & (n - 1)) + +int main() +{ + printf("Hello World\n"); + + for(int i = 0; i < 100; i++) + printf("value of %d modulo 8 is: %d\n", i, modulo(i,10)); + + return 0; +} diff --git a/algorithms/bit-manipulation/subtraction.c b/algorithms/bit-manipulation/subtraction.c new file mode 100644 index 00000000..989ac555 --- /dev/null +++ b/algorithms/bit-manipulation/subtraction.c @@ -0,0 +1,18 @@ +#include + +int subtract(int x, int y) +{ + while(y != 0) + { + unsigned int borrow = y & ~x; + x = y ^ x; + y = borrow << 1; + } + return x; +} + +int main() +{ + printf("diff of %d and %d is %d\n", 4, 3, subtract(4, 3)); + return 0; +} \ No newline at end of file