What functions can bitwise Operations implement?

Source: Internet
Author: User

What functions can bitwise Operations implement?

What functions can bitwise Operations implement?

In many cases, bitwise operations are recommended to reduce the time complexity of the algorithm. Today, let's sort out the functions that bitwise operations can implement.


1. multiplication and division 2


Shift 1 to 2 and shift n to 2 to 2;

Shift 1 to 2 and shift n to 2 to 2;


For example:

# Include <iostream> using namespace std; int main () {int a = 16; int B = 25; // multiply by 2 cout <(B <1) <''<(a> 1) <endl; return 0 ;}


2. Determine the parity


Use bitwise AND and 1 bitwise AND in place operations.

As follows:


# Include <iostream> using namespace std; int main () {int a = 16; int B = 25; // judge the parity if (a & 1) cout <"Odd" <endl; elsecout <"Even" <endl; return 0 ;}


3. remainder operation


We still use the bitwise AND operator, but it is no longer a bitwise AND.

# Include <iostream> using namespace std; int main () {int a = 16; int B = 25; // obtain cout <(a & 3) <endl; // cout divided by the remainder of 4 <(a & 7) <endl; // divided by the remainder of 8 <(a & 8) <endl; // invalid, returns 0 ;}

Analysis: note that this method can only calculate the remainder of the power of 2, and the result of bitwise AND can only be 2 ^ n-1, because the binary form of these numbers is 1.


4. Calculate the inverse number

Use bitwise inverse operators.

// Calculate the opposite number cout <(~ A + 1) <endl;


5. Calculate the absolute value using the XOR operator (^)

# Include <iostream> using namespace std; int main () {int a =-36; int B = 25; // absolute value int tmp = a> 31; /// when a is greater than or equal to 0, tmp is 0. When a is less than 0, tmp is-1 int A = (a ^ tmp)-tmp; cout <A <endl; return 0 ;}


These basic mathematical operations can be implemented by using operators, which are relatively low in time complexity and will be commonly used in the future.




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.