Details the bitwise operators in the Python language

Source: Internet
Author: User
A bitwise operator computes a number as a binary. The bitwise algorithms in Python are as follows:

Bitwise with (bitwise AND of x and Y)

& Example: 5&3 = 1 Explanation: 101 11 The same bit is only digit 1, so the result is 1

bitwise OR (bitwise OR of x and Y)

| Example: 5|3 = 7 Explanation: 101 11 The bit that appears 1 is 1 1 1, so the result is 111

Bitwise XOR (bitwise exclusive OR of x and Y)

^ Example: 5^3 = 6 Explanation: 101 11 The bitwise addition (not rounding) is 1 1 0, the result is 110

Bitwise reversal (The bits of x inverted)

~ Example: 6 Explanation: Multiply the binary number +1 by-1, i.e. ~x =-(X+1),-(101 + 1) = 110

A bitwise reversal can only be used in front of a number. So writing 3+~5 can get the result-3, it's wrong to write a.

Bitwise left SHIFT (X shifted ieft by n bits)

<< Example: 5<<2 = 20 Explanation: 101 Move 2 bits to the left to get 10100, that is, the right more than 2 bits with 0 complement

Bitwise right SHIFT (X shifted r by n bits)

>> Example: 5>>2 = 1 Explanation: 101 move 2 bits to the right to get 1, that is, remove the 2-bit

  • 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.