Use equal-bit operators to perform addition operations

Source: Internet
Author: User

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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.