Title Description
How do I use bitwise operations to implement subtraction four operations of integers separately?
Solution Solutions
You need to be familiar with the bit operation implementations of some common functions, specifically:
<1> Common equation:-n = ~ (n-1) = ~n+1
<2> gets the last 1:n& (-N) or n&~ (n-1) in the binary of the integer n, such as: n=010100, then-n=101100,n& (-N) =000100
<3> Remove the last 1:n& (n-1) from the binary of integer n, such as:n=010100,n-1=010011,n& (n-1) =010000
(1) Addition implementation
It is easy to implement integer addition operations with "XOR" and "or" operations: the "XOR operation" of the corresponding bit can get the numeric value of the bit, and the "and operation" of the corresponding bit can get the high carry that the bit produces, such as: a=010010,b=100111, the calculation steps are as follows:
First round: a^b=110101, (A&b) <<1=000100, due to carry (000100) greater than 0, then into the next round of calculations, a=110101,b=000100,a^b=110001, (A&B) < <1=001000, since carry is greater than 0, it goes to the next round of calculations: a=110001,b=001000,a^b=111001, (A&B) <<1=0, carry 0, terminating, calculated as: 111001.
The code is as follows:
int add (int a, int b) {
int carry, add;
do {
add = a ^ b;
Carry = (A & B) << 1;
A = add;
b = Carry;
} while (Carry! = 0);
return add;
}
Code two:
int Add (int x, int y)
{
if (0 = = y) return x;
int sum = x ^ y;int carry = (x & y) << 1;return Add(sum, carry);
}
(2) Subtraction implementation
Subtraction can easily be converted to addition: A-B = a + (-i) = a + (~b + 1)
The code is as follows:
int subtract (int a, int b) {
Return Add (A, add (~b, 1));
}
(3) Multiplication implementation
First look at an example: 1011*1010:
1011
* 1010
10110 < 左移一位,乘以0010
+ 1011000 < Left 3 bit, multiplied by 1000
1101110
Thus multiplication can be accomplished through series shift and addition. The last 1 can be obtained by b&~ (b-1), can be removed by b& (b-1), in order to effectively get the left shift of the number of digits, you can calculate a map in advance, the code is as follows:
int multiply (int a, int b) {
BOOL Neg = (b < 0);
if (b < 0)
b =-C;
int sum = 0;
Map
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Bit operation implementation subtraction arithmetic