Computer Science

Python Bitwise Operators

Python Bitwise Operators are used to perform bitwise operations on integers. These operators work on the individual bits of the operands. The bitwise operators include AND, OR, XOR, NOT, left shift, and right shift.

Written by Perlego with AI-assistance

8 Key excerpts on "Python Bitwise Operators"

  • Book cover image for: Data Analysis with Python
    eBook - ePub

    Data Analysis with Python

    Introducing NumPy, Pandas, Matplotlib, and Essential Elements of Python Programming (English Edition)

    Bitwise operators are used to perform bit-by-bit operations on integers in Python. First, they convert the Python integer value of operands into binary; then, they execute the mentioned Bitwise operation after getting the binary result. They translate the final value back into an integer, and return that integer value as a result.
    Various Bitwise operators in Python have been depicted as follows:
    Operator name Operator symbol Description Example
    Bitwise AND & performs bit by bit AND operation on the bits of binary value left and right operands a & b
    Bitwise OR | perform bit by bit OR operation on the bits of binary value left and right operands a | b
    Bitwise NOT ~ one’s complement in Python means it gives – (binary value of operand +1) in decimal ~a means –(binary value of a+1)
    Bitwise XOR ^ perform bit by bit XOR operation on the bits of binary value left and right operands a ^ b
    Bitwise right shift >> left operand shifted towards the right by the bits mentioned in the right operand a>>1
    Bitwise left shift << left operand shifted towards left by the bits mentioned in right operand a<<1
    Table 3.5: Bitwise Operators in Python
    Now, we will see how the bitwise operators can be applied on variables a and b: Coding Example(s) a = 10  # 1010 b = 8   #1000 #Bitwise AND (&) print(“Bitwise AND (&) => a & b ->”,a & b) #Bitwise OR (|) print(“Bitwise OR (|) => a | b ->”,a | b) #Bitwise NOT (~) print(“Bitwise NOT (~) =>  ~ b ->”, ~ b)  # -(1000+1) = -(1001) = -(9) #Bitwise XOR (^) print(“Bitwise XOR (^) => a ^ b ->”,a ^ b) #Bitwise right shift (>>) print(“Bitwise right shift by one bit (>>) => a >> b ->”,a >> 1) #Bitwise left shift (<<) print(“Bitwise left shift by one bit (<<) => a << b ->”,a << 1) Output Bitwise AND (&) => a & b -> 8 Bitwise OR (|) => a | b -> 10 Bitwise NOT (~) =>  ~ b -> -9 Bitwise XOR (^) => a ^ b -> 2 Bitwise right shift by one bit (>>) => a >> b -> 5 Bitwise left shift by one bit (<<) => a << b -> 20

    Membership operators

    These operators are used to check the membership with a sequence in Python (list, string, tuple, and so on). Please check the following table of membership operators in Python:
  • Book cover image for: Basic Core Python Programming
    eBook - ePub

    Basic Core Python Programming

    A Complete Reference Book to Master Python with Practical Applications (English Edition)

    In Python, the following bit by bit operations are defined: Operator Purpose & Binary AND | Binary OR ^ Binary XOR. ~ Binary Ones Complement. << Binary Left Shift >> Binary Right Shift Table 3.8: Bitwise operators and their purpose 3.3.5.1 Binary AND This operator copies a bit to the result if it exists in both operands, for example: 2 = 010 5 = 101 2 & 5 = 010 & 101 = 000 = 0 >>> a = 2 >>> b = 5 >>> a & b 0 >>> 3.3.5.2 Binary OR It copies a bit to the result if it exists in either operand, for example: 2 = 010 5 = 101 2 | 5 = 010|101 = 111 = 7 >>> a = 2 >>> b = 5 >>> a|b 7 >>> 3.3.5.3 Binary XOR It copies the bit if it is set in one operand but not both. 2 = 010 5 = 101 2 ^ 5 = 010 ^101 = 111 = 7 >>> a = 2 >>> b = 5 >>> a ^ b 7 >>> 3.3.5.4 Binary ones complement This operator is unary and has the effect of toggling all bits. 2 = 010 ~2. = ~010 2 0 0 0 0 0 0 1 0 Therefore, ~2 = -3 1 1 1 1 1 1 0 1 You should get the same output on the shell as shown in the following box: >>> ~a -3 3.3.5.5 Binary left shift The left operand’s value is moved left by the number of bits specified by the right operand. For example: 2 = 010 5 = 101 2 << 1 = 010 << 1 = 100 = 4 5 << 1 = 101 << 1 = 1010 = 10 The following box shows how this would work in Python: >>> # assign a = 2 >>> a = 2 >>> a << 1 4 >>> # assign b = 5 >>> a = 5 >>>a << 1 10 >>> 3.3.5.6 Binary right shift The left operand’s value is moved right by the number of bits specified by the right operand. 2 = 010 5 = 101 2 >> 1 = 010 >>1 = 001 = 1 5 >> 1 = 101 >> 1 = 0010 = 2 >>># assign a = 2 >>>a = 2 >>>a >> 1 1 >>># assign b = 5 >>>a = 5 >>>a >> 1 2 >>> 3.3.6 Membership operators Membership operators are used to check the membership of a value in a sequence. You will learn to work with these operators in chapters related to strings, lists, or tuples
  • Book cover image for: Maya Python for Games and Film
    eBook - PDF

    Maya Python for Games and Film

    A Complete Reference for the Maya Python API

    • Adam Mechtley, Ryan Trowbridge(Authors)
    • 2011(Publication Date)
    • CRC Press
      (Publisher)
    Boolean and Bitwise Operators Some operators are especially important when you are working with Boolean values. You will use these operators widely in Chapter 3 as we discuss using conditional statements to control program flow. In Table 2.3 Working with Booleans 45 we have consolidated the most common operators from tables in Sections 5.2 and 5.4.1 of Python Standard Library. When working with Boolean variables, the bitwise operators for and ( & ) and or ( | ) function just like their Boolean operator equivalents. The exclu-sive-or operator ( ^ ), however, will only return True if either x or y is True, but will return False if they are both True or both False. There are more bitwise operators that we have not shown here only because we do not use them throughout this text. Programmers who are comfortable with binary number systems should be aware that bitwise operators also work with int and long types. 3 WORKING WITH SEQUENCE TYPES In Chapter 1, three of the variable types introduced can be called sequence types. Sequence types include strings, lists, and tuples. These types basically contain a group of data in a linear sequence. While each of these types is obviously unique, they also share some properties, which we briefly discuss in this section. Operators As with numbers and Booleans, sequence types have a set of operators that allow you to work with them conveniently. Section 5.6 of Python Standard Library has a table of operations usable with sequence types. We have selected the most common of these operations to display in Table 2.4. Because they are perhaps not as immediately obvious as math operators, some merit a bit of discussion.
  • Book cover image for: Python Internals for Developers
    eBook - ePub

    Python Internals for Developers

    Practice Python 3.x Fundamentals, Including Data Structures, Asymptotic Analysis, and Data Types

    Table 1.7 describes the various Python membership operators:
    Operator Description
    in Outputs True if left operand is part of right operand.
    not in Outputs True if left operand is not part of right operand.
    Table 1.7: Python membership operators
    Example 1.9: Membership operators
    1. ’e’ in ‘hello’
      //Output True
    2. ‘z’ in ‘hello’
      //Output False
    3. ‘z’ not in ‘hello’
      //Output True
    4. ‘e’ not in ‘hello’
      //Output False

    Bitwise operators

    Bitwise operators operate on each bit of number. Bitwise operator converts operands to a binary number, performs operations on each bit, converts the binary output to a decimal number, and outputs decimal number. Table 1.8 describes the various Python membership operators:
    Operator Name Description
    & Bitwise AND It is a binary operator. It compares bits of both the binary numbers and sets the output bit to 1 if both the bits are 1.
    | Bitwise OR It is a binary operator. It compares bits of both the binary numbers and sets the output bit to 1 if any of the bit is 1.
    ^ Bitwise XOR It is a binary operator. It compares bits of both the binary numbers and sets the output bit to 1 if any one bit is 1. If both the bits are 0 or 1, then it sets the output bit to 0.
    ~ Bitwise NOT It is a unary operator. It sets the output bit to 0 if the input bit is 1 and vice versa.
    << Left Shift
    It is a binary operator. The left operand is the number to be shifted and the right operand is the number of bits to be shifted. Shifts all bits to the left by the number of positions as mentioned in the right operand. Fills the rightmost bits by 0.
    >> Right Shift
    It is a binary operator. The left operand is the number to be shifted and the right operand is the number of bits to be shifted. It shifts all bits to the right by the number of positions as mentioned in the right operand and removes the rightmost bit. It fills the leftmost bits by 0.
  • Book cover image for: Handbook of Computer Programming with Python
    • Dimitrios Xanthidis, Christos Manolas, Ourania K. Xanthidou, Han-I Wang, Dimitrios Xanthidis, Christos Manolas, Ourania K. Xanthidou, Han-I Wang(Authors)
    • 2022(Publication Date)
    {:04b} must be used in order to display the binary value with four digits.
    TABLE 2.7 Python Bitwise Operators
    Operator Example Name Description
    &. | a & b, a | b bitwise AND, OR Each bit position in the result is the logical AND (or OR) of the bits in the corresponding position of the operands; 1 if both are 1, otherwise 0 for AND; 1 if either is 1, otherwise 0.
    ~ ~a bitwise negation Each bit position in the result is the logical negation of the bit in the corresponding position of the operand; 1 if 0, 0 if 1.
    ^ a ^ b bitwise XOR (exclusive OR) Each bit position in the result is the logical XOR of the bits in the corresponding position of the operands; 1 if the bits in the operands are different, 0 if they are the same.
    >>, << a >> n, a << n Shift right or left n places Each bit is shifted right or left by n places.
    1 # Bitwise 'and' 2 a, b = 0b1100, 0b1010 3 print('0b{:04b}'.format(a & b)) 4 5 # Bitwise 'and' 6 a, b, c, = 12, 10, 0 # 12 = 0b1100, 10 = 0b1010 7 C = a & b # 8 = 0b1000 8 print('Value of c is', c) 9 10 # Bitwise 'or' 11 a, b = 0b1100, 0b1010 12 print('0b{:04b}'.format(a | b)) 13 14 # Bitwise 'or' 15 a, b, c, = 12, 10, 0 # 10 = 0b1100, 12 = 0b1010 16 c = a | b # 14 = 0b1110 17 print('Value of c is', c) 18 19 # Bitwise negation 20 a = 0b1100 21 b = ~a 22 print('0b{:04b}'.format(b)) 23 24 # Bitwise negation
  • Book cover image for: Machine Learning For Dummies
    • John Paul Mueller, Luca Massaron(Authors)
    • 2021(Publication Date)
    • For Dummies
      (Publisher)
    value of the right operand by the left operand 5 ** 2 = 25 // Performs integer division, in which the left operand is divided by the right operand and only the whole number is returned (also called floor division) 5 // 2 = 2 ~ Inverts the bits in a number so that all of the 0 bits become 1 bits and vice versa. ~4 results in a value of –5 (continued) 70 PART 2 Preparing Your Learning Tools Sometimes you need to check the relationship between two variables or compare them in some fashion. Table 5-4 provides a listing of Python relational and logical operators. TABLE 5-4 Python Relational and Logical Operators Operator Description Example == Determines whether two values are equal. Notice that the relational operator uses two equals signs. A mistake that many developers make is to use just one equals sign, which results in one value being assigned to another. 1 == 2 is False != Determines whether two values are not equal. Some older versions of Python allowed you to use the <> operator in place of the != operator. Using the <> operator results in an error in current versions of Python. 1 != 2 is True Operator Description Example – Negates the original value so that positive becomes negative and vice versa. –(–4) results in 4 and –4 results in –4 Is provided purely for the sake of completeness. This operator returns the same value that you provide as input. 4 results in a value of 4 & (And) Determines whether both individual bits within two operators are true and sets the resulting bit to True when they are. 0b1100 & 0b0110 = 0b0100 | (Or) Determines whether either of the individual bits within two operators are true and sets the resulting bit to True when they are. 0b1100 | 0b0110 = 0b1110 ^ (Exclusive or) Determines whether just one of the individual bits within two operators is true and sets the resulting bit to True when one is. When both bits are true or both bits are false, the result is False .
  • Book cover image for: An Introduction to Python Programming: A Practical Approach
    eBook - ePub

    An Introduction to Python Programming: A Practical Approach

    step-by-step approach to Python programming with machine learning fundamental and theoretical principles.

    • Dr. Krishna Kumar Mohbey; Dr. Brijesh Bakariya(Author)
    • 2021(Publication Date)
    • BPB Publications
      (Publisher)
    - ). Let us take an example to understand unary operators.
    Example 2.4: x = 10 print ("Unary positive operator", +x) print ("Unary Negative operator", -x) Output: Unary positive operator 10 Unary Negative operator -10

    Bitwise operators

    Bitwise operator works on bits and performs bit-by-bit operation.
    Suppose x = 26 and y = 18 , then the binary conversion of x and y is 11010, 10010. Let us understand the various bitwise operations on x and y with their results:
    x= 11010 y= 10010 x & y = 10010 x | y = 11010 x ^ y = 01000 ~x = 00101 ~y = 01101 There are the following Bitwise operators:
    • Binary AND (&) : This operator copies a bit to the result if it exists in both operands.
    • Binary OR (|) : This operator copies a bit if it exists in either operand.
    • Binary XOR (^) : This operator copies the bit if it is set in one operand but not both.
    • Binary One's Complement (~) : It is unary and has the effect of flipping bits.
    • Binary Left Shift (<<) : In this operator, the left operand's value is moved left by the number of bits specified by the right operand.
    • Binary Right Shift (>>) : In this operator the left operands value is moved right by the number of bits specified by the right operand.
    Let us take an example to understand all bitwise operators. Example 2.5: x = 26            # 26 = 11010 y = 18            # 18 = 10010 z = 0 z = x & y, print ("1 - Value of z is ", z) z = x | y, print ("2 - Value of z is ", z) z = x ^ y, print ("3 - Value of z is ", z) z = ~x, print ("4 - Value of z is ", z) z = x << 2, print ("5 - Value of z is ", z) z = x >> 2, print ("6 - Value of z is ", z)
    Output :
    1 - Value of z is  18 2 - Value of z is  26 3 - Value of z is  8 4 - Value of z is  -27 5 - Value of z is  104 6 - Value of z is  6

    Logical operators

    Logical operators are used to perform arithmetic and logical computations. These are special symbols (AND , OR , and NOT
  • Book cover image for: A Functional Start to Computing with Python
    Thus, 100+100 re-duces to 200. Computing long ago parted ways with calculations of numerical results. Most of what computers do is search, organize data, find patterns, and sense physical objects. Nevertheless, because most students have learned some algebra, it is reasonable to first introduce Python’s numeric operators, and then ease into the less familiar operations. Unlike low level machine language working with bits, the operators in Python will not work unless types of data are suitable: Python is a typed language. Python outputs a TypeError message when you try to use an operator on the wrong type of data. Operators are of two flavors, binary and unary. Binary operators, like * and / , take two arguments placed on the left and right sides of the operator. Unary operators have just one argument placed on the right side of the operator. This chapter starts with familiar numeric operators, then goes on to introduce new ones for boolean and sequence types. After these operators are presented, Chapter 7 shows how operations can be mixed in expressions, and how operator priority helps to resolve ambiguity. Notation used in this and later chapters is the “ ➜ ” symbol, which indicates how Python evaluates an operation or expression, reducing it to an output value. Example: 100+100 ➜ 200 . Numeric: Float and Integer Arithmetic Numeric operators take integer or floating point arguments and compute a result. Most often, both left and right arguments to an operator have the same numeric type (integer or floating point), but it is possible to mix these as well, putting an integer on the left side and a float (floating point) on the right side or the other way around. A few numeric operators are specialized to integers; the section following this one deals with these.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.