Performing arithmetic operations in binary using only bitwise operators [duplicate]

徘徊边缘 提交于 2019-11-29 08:55:15
Rivasa

Well, subtracting in bitwise operations without the + or - operators is slightly tricky, but can be done. You have the basic idea with the complement, but without using + it becomes slightly tricky.

You can do it by first setting up addition with bit-wise only, then using that, you can do subtraction. Which is used for the complement, So the code looks like this:

int badd(int n1, int n2){
    int carry, sum;
    carry = (n1 & n2) << 1; // Find bits that are used for carry
    sum = n1 ^ n2; // Add each bit, discard carry.
    if (sum & carry) // If bits match, add current sum and carry.
        return badd(sum, carry);
    else
        return sum ^ carry; // Return the sum.
}

int bsub(int n1, int n2){
    // Add two's complement and return.
    return badd(n1, badd(~n2, 1));
}

And then if we use the above code in an example:

int main(){
printf("%d\n", bsub(53, 17));
return 0;
}

Which ends up returning 36. And that is how subtraction works with bitwise only operations.

Afterwards multiplication and division get more complicated, but can be done; for those two operations, use shifts along with addition and/or subtraction to get the job done. You may also want to read this question and this article on how to do it.

You have to implement the binary addition first:

Example with 4 bits:

a = 1101 b = 1011

mask will range from 0001 to 1000

for (i=0;i<4;i++) {
    x = a & pow(2, i); //mask, you can shift left as well
    y = b & pow(2, i);
    z = x ^ y; //XOR to calculate addition
    z = z ^ carry; //add previous carry
    carry = x & y | x ^ carry | y ^ carry; //new carry
}

This is pseudocode. The mask allows for operating bit by bit from left to right. You'll have to store z conveniently into another variable.

Once you have the addition, you'll be able to implement subtraction by 1'complementing and adding 1.

Multiplication goes the same way, but slightly more difficult. Basically it's the same division method you learned at school, using masks to select bits conveniently and adding the intermediate results using the addition above.

Division is a bit more complicated, it would take some more time to explain but basically it's the same principle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!