Last active
December 2, 2023 16:55
-
-
Save hamza-cskn/947a248ebad029eaa5c59f2715347488 to your computer and use it in GitHub Desktop.
Multiply and sum implementations using only bitwise operators. (negative numbers are not supported.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int get_bit(int val, int bit) { | |
return (val >> bit) & 1; | |
} | |
/* sets ith bit to zero*/ | |
int set_zero_bit(int val, int i) { | |
return val & (~(1 << i)); | |
} | |
/* sets ith bit to one*/ | |
int set_one_bit(int val, int i) { | |
return val | (1 << i); | |
} | |
/* adds 2^i to a */ | |
int power_of_two_sum(int a, int i) { | |
int bit; | |
int total_bits = sizeof(int) * 8; | |
while (i < total_bits && (bit = get_bit(a, i))) { | |
a = set_zero_bit(a, i); | |
i++; | |
} | |
if (i >= total_bits) | |
return -1; | |
return set_one_bit(a, i); | |
} | |
int implemented_sum(int a, int b) { | |
int i = 0; | |
int total_bits = sizeof(int) * 8; | |
int result = a; | |
while (i < total_bits) { | |
int bit = get_bit(b, i); | |
if (bit == 1) | |
result = power_of_two_sum(result, i); | |
i++; | |
} | |
return result; | |
} | |
int implemented_multiply(int a, int b) { | |
int bits = sizeof(int) * 8; | |
int result = 0; | |
for (int i = 0; i < bits; i++) { | |
if (get_bit(b, i) == 1) { | |
result = implemented_sum(result, a << i); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment