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

7 Key excerpts on "Python Bitwise Operators"

  • 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
  • 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:
  • 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
  • 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.
  • Dashboard Design
    eBook - ePub
    • Michael Burch, Marco Schmid(Authors)
    • 2024(Publication Date)
    • River Publishers
      (Publisher)
    Table 4.6 .
    Table 4.6 Bitwise operators, examples, their meanings, and binary versus decimal.
    Operator Example Explanation Binary Decimal
    & x & y bitwise and 010 & 110 = 010 2&6=2
    | x | y bitwise or 010 | 110 = 110 2|6=6
    ∼ x bitwise negation 010 = 101 2=5
    x∧y bitwise xor 010 110 = 100 2 6=4
    » x » n n bitwise right shift 010 »1=001 2»1=1
    « x « n n bitwise left shift 010 «1=100 2«1=4
    A more complex example for a bitwise expression would be something like the expression in Listing 4.4 .

    Listing 4.4 A bitwise expression

    1 16 << 3 | 255 >> 2 # evaluates to 191
    Exercise
    • Exercise 4.1.4.1: Evaluate the following bitwise expression:
      1 5 & 13 & 3 | 14
    • Exercise 4.1.4.2: Evaluate the following bitwise expression:
      1 23 >> 2 & 23 | (~17)

    4.1.5 Mixed expressions

    Actually, expressions can exist in various forms composed of subexpressions based on operands of several datatypes like integers, floating point numbers,
    Booleans, but even Strings, or more complex objects. Also, the operators themselves can fall into the categories of arithmetic, relational, Boolean/logi-cal, or bitwise operators. Such expressions are denoted in this book as mixed expressions. In cases in which an expression has a mixed character, we must understand the precedence of the individual operators which is given as an overview inTable 4.7
  • 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
  • Introduction to Java Programming, 2nd Edition
    These operators are the least commonly used operators. Some of the bitwise operators are categorized under bitwise logical operators and these are discussed next.  
    The Bitwise Compliment (~) Operator
    The bitwise Compliment (~ ) operator comes under the category of bitwise logical operators. The ~ operator inverts all bits of its operand; for example, 0 becomes 1 and 1 becomes 0. This operator is also known as the bitwise unary NOT operator. The syntax for using the compliment (~ ) operator is as follows:
      ~ value or expression;   For example:   int a = 3; int b = ~a;  
    In this example, 3 is assigned to the integer variable a as an initial value, which is stored in the computer’s memory as 00000011. In the next statement, ~ operator is used with the integer variable a . This operator inverts all the bits 00000011 of the value 3 into 11111100. Then, the resultant value is assigned to the integer variable b .
     
    The Bitwise AND (&) Operator
    The bitwise AND (& ) operator also comes under the category of bitwise logical operators. If both the operands consist of the value 1, then the & operator will produce bit 1 as the result. But, if one or both the operands consist of the value 0, then the & operator will produce 0 as the result.
     
    The syntax for using the & operator is as follows:
      operand1 & operand2;  
    For example, you can use the AND (& ) operator with two operands: 23 and 15, as given next:
      00010111//Bits representing the value 23 & 00001111//Bits representing the value 15 -------- 00000111//Bits representing the value 7  
    The Bitwise OR (|) Operator
    The bitwise OR (| ) operator also comes under the category of bitwise logical operators. If one or both the operands consist of the value 1, then the | operator will produce bit 1 as the result. But, if both the operands contain 0, then the | operator will produce 0 as the result. The syntax for using the |
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.