Detailed introduction to the bitwise operators in Python

Source: Internet
Author: User

Bitwise operators regard numbers as binary values for calculation. The bitwise Algorithm in Python is as follows:

Bitwise and of x and y)

& Example: 5 & 3 = 1 explanation: 101 11 the same bit is only a single bit, so the result is 1

Bitwise or of x and y)

| Example: 5 | 3 = 7 explanation: the occurrence of 1 in 101 11 is 1 1, so the result is 111.

Bitwise exclusive or of x and y)

^ Example: 5 ^ 3 = 6 explanation: 101 11 ing addition (not carry) is 1 1 0, so the result is 110

The bits of x inverted)

~ Example :~ 5 =-6 explanation: multiply the binary number + 1 by-1, that is ~ X =-(x + 1),-(101 + 1) =-110

Bitwise inversion can only be used before a number. Therefore, it is written as 3 + ~ 5. You can get the result-3, which is written as 3 ~ 5. An error occurred.

Shift left by bit (x shifted left by n bits)

<Example: 5 <2 = 20 explanation: 101 moves two places to the left to get 10100, that is, two more places on the right are supplemented with 0.

Shift right by bit (x shifted right by n bits)

> Example: 5> 2 = 1 explanation: 101 move two places to the right to get 1, that is, remove the two places on the right.

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.