Anyone who has learned C language knows that bit operations are always faster than arithmetic operations when writing code again,
This article uses the bitwise operation provided by C language to add two numbers.
The code used in this article has been debugged and can run normally. In the debugging environment centos GCC, the code is implemented and the test results are as follows:
# Include <stdio. h> # include <stdlib. h> int main (INT argc, char ** argv) {int add_a, add_ B; int sum; If (3! = Argc) printf ("Usage: bin_add, (# add_1) (# add_d) \ n"); else {add_a = atoi (argv [1]); add_ B = atoi (argv [2]); sum = add (add_a, add_ B); printf ("(% d) + (% d) = % d \ n", add_a, add_ B, sum);} return 0;} int add (INT temp_a, int temp_ B) {int temp_c = 0; int temp_d = 0; temp_c = temp_a & temp_ B; // obtain the bitwise temp_d = temp_a ^ temp_ B; // obtain the bitwise temp_d and while (temp_c) {temp_c <= 1; temp_ B = temp_c; temp_a = temp_d; temp_c = temp_a & temp_ B; temp_d = temp_a ^ temp_ B;} return temp_d ;}
Code test:
[[email protected] Destop]$ gcc -o bin_add test.c[[email protected] Destop]$ ./bin_add 10 789(10)+(789)=799[[email protected] Destop]$ ./bin_add 1234 4567(1234)+(4567)=5801[[email protected] Destop]$ ./bin_add 1234 -456(1234)+(-456)=778[[email protected] Destop]$ ./bin_add -34 -456(-34)+(-456)=-490
In fact, the main solution is to separate the "standard and" and "carry and" in the addition process. You can add the carry to your position at a time.