Created
February 12, 2019 08:39
-
-
Save rgb-24bit/c003e538179e8618cddbb51c5f0ba676 to your computer and use it in GitHub Desktop.
Incremental addition, subtraction, multiplication and division of integers by bit operations
This file contains 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
#include <stdio.h> | |
#include <stdlib.h> | |
int plus(int a, int b) { | |
int sum = a, carry = b; | |
while (carry) { | |
int temp = sum; | |
sum = temp ^ carry; | |
carry = (temp & carry) << 1; | |
} | |
return sum; | |
} | |
int negate(int num) { | |
return plus(~num, 1); | |
} | |
int abs(int num) { | |
return num < 0 ? negate(num) : num; | |
} | |
int subtract(int a, int b) { | |
return plus(a, negate(b)); | |
} | |
int multiply(int a, int b) { | |
int multiplier = abs(a), multiplicand = abs(b); | |
int product = 0; | |
while (multiplicand) { | |
if (multiplicand & 0x1) { | |
product = plus(product, multiplier); | |
} | |
multiplier = multiplier << 1; | |
multiplicand = multiplicand >> 1; | |
} | |
if ((a ^ b) < 0) { | |
product = negate(product); | |
} | |
return product; | |
} | |
int bitlength(int a) { | |
int length = 0; | |
while (a) { | |
length = plus(length, 1); | |
a = a >> 1; | |
} | |
return length; | |
} | |
int lengthdiff(int a, int b) { | |
return subtract(bitlength(a), bitlength(b)); | |
} | |
int division(int a, int b) { | |
int dividend = abs(a), divisor = abs(b); | |
int quotient = 0; | |
for (int i = lengthdiff(dividend, divisor); i >= 0; i = subtract(i, 1)) { | |
int r = (divisor << i); | |
// Left shift divisor until it's smaller than dividend | |
if (r <= dividend) { | |
quotient |= (1 << i); | |
dividend = subtract(dividend, (int) r); | |
} | |
} | |
if ((a ^ b) < 0) { | |
quotient = negate(quotient); | |
} | |
return quotient; | |
} | |
int remain(int a, int b) { | |
int dividend = abs(a), divisor = abs(b); | |
int quotient = 0; | |
for (int i = lengthdiff(dividend, divisor); i >= 0; i = subtract(i, 1)) { | |
int r = (divisor << i); | |
// Left shift divisor until it's smaller than dividend | |
if (r <= dividend) { | |
dividend = subtract(dividend, (int) r); | |
} | |
} | |
if (a < 0) { | |
dividend = negate(dividend); | |
} | |
return dividend; | |
} | |
int main(int argc, char* argv[]) { | |
int a = atoi(argv[1]), b = atoi(argv[2]); | |
printf("plus: %d, subtract: %d, multiply: %d, division: %d, remainder: %d", | |
plus(a, b), subtract(a, b), multiply(a, b), division(a, b), remain(a, b)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment