Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python bitwise operators methods

#PYTHON BITWISE OPERATORS
OPERATOR	DESCRIPTION	        SYNTAX  FUNCTION        IN-PLACE METHOD
&	        Bitwise AND	        a & b   and_(a, b)      __and__(self, other)
|	        Bitwise OR	        a | b   or_(a, b)       __or__(self, other)
^	        Bitwise XOR	        a ^ b   xor(a, b)       __xor__(self, other)
~           Bitwise NOT         ~ a     invert(a)       __invert__(self)
<<          Bitwise L shift     a << b  lshift(a, b)    __lshift__(self, other)
>>          Bitwise R shift     a >> b  rshift(a, b)    __irshift__(self, other)
Comment

python bitwise operators

x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
x & y
Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.
x | y
Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
~ x
Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.
x ^ y
Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.
Comment

bitwise operators python

OPERATOR DESCRIPTION	      SYNTAX
&	     Bitwise AND          x & y
|	     Bitwise OR           x | y
~	     Bitwise NOT	      ~x
^	     Bitwise XOR	      x ^ y
>>		 Bitwise right shift  x>>
<<		 Bitwise left shift	  x<<
Comment

python bitwise operators

<int> = <int> & <int>                    # And (0b1100 & 0b1010 == 0b1000).
<int> = <int> | <int>                    # Or  (0b1100 | 0b1010 == 0b1110).
<int> = <int> ^ <int>                    # Xor (0b1100 ^ 0b1010 == 0b0110).
<int> = <int> << n_bits                  # Left shift (>> for right).
<int> = ~<int>                           # Not (also: -<int> - 1).
Comment

bitwise operators in python

# Examples of Bitwise operators
a = 10
b = 4
 
# Print bitwise AND operation
print(a & b)
 
# Print bitwise OR operation
print(a | b)
 
# Print bitwise NOT operation
print(~a)
 
# print bitwise XOR operation
print(a ^ b)
 
# print bitwise right shift operation
print(a >> 2)
 
# print bitwise left shift operation
print(a << 2)
Comment

bitwise operation in python

"""
 BITWISE OPERATION FILE: MAINTAINING CRUD BITWISE OPERAITON;

"""


def getBit(number, shift):
    """
    GET_BIT: RETURN PARTICULAR BIT OF NUMBER PLACED AT 'i' POSITION;
    """
    if number and shift >= 0:
        mask = number >> shift
        return (mask & 1)
    else:
        return None


def setBit(number, position):
    """
    SET_BIT: RETURN PARTICULAR BIT OF NUMBER PLACED AT 'i' POSITION;
    """
    if number and (position >= 0):
        mask = 1 << position
        return (mask | number)
    else:
        return None


def clearBit(number, position):
    """
    CLEAR_BIT: CLEAR PARTICULAR BIT OF NUMBER PLACED AT 'i' POSITION;
    """
    if number and (position >= 0):
        mask = ~(1 << position)
        return mask & number
    else:
        return None


def updateBit(number, position, value):
    """
    UPDATE_BIT: UPDATE PARTICULAR BIT OF NUMBER PLACED AT 'i' POSITION;
    """
    if (number and (position >= 0) and (value == 0 or 1)):
        ## Mask that ha set bit at particular place;
        mask = ~(1 << position)
        return (number & mask | value << position)
    else:
        return None


def clearBitTillPosition(number, position):
    """
    CLEAR_BIT_TILL_POSITION: DELETE ALL BIT TILL POSITION 'K';
    """
    if (number and (position >= 0)):
        mask = -1 << position
        return mask & number
    else:
        return None


def removeBitRange(number, start, end):
    """
    REMOVE_BIT_RANGE: DELETE ALL BIT FROM INDEX START TO END;
    """
    if (number and start >= 0 and end >= 0):

        leftMask = ~0 << end + 1

        rightMask = (1 << start) - 1

        mask = leftMask | rightMask

        return mask & number
    else:
        return None


## COUNT THE SET BIT IN NUMBER HACK;
def countBitHack(number):
    if number != None:
        count = 0
        while (number > 0):
            number = (number & number - 1)
            count += 1

        return count
    else:
        return None


## COUNT THE SET BIT IN NUMBER;
def countBit(number):
    if number != None:
        count = 0
        while (number > 0):
            count += number & 1
            number = number >> 1

        return count
    else:
        return None


## POWER OF 2
def powerOfTwo(number):
    if number == 0:
        return 0
    elif number > 0:
        if (number & number - 1) == 0:
            return True
        return False
    else:
        return False


## FAST EXPONENTIAL OF NUMBER;
def fastExpo(num, pow):
    if (num and pow):
        result = 1  # result = 1
        while (pow > 0):
            lastBit = (pow & 1)  # bit = 11001
            if lastBit:
                result = result * num
            num = num * num
            pow = (pow >> 1)

        return result
    else:
        return None


## CONVERT INTEGER TO BINARY;
def convertIntToBin(number):
    base = 10
    pow = 1
    result = 0
    while (number > 0):
        lastBit = number & 1  ## Taking Out Last Bit;
        result += lastBit * pow
        pow = pow * base
        number = number >> 1  ## Removing Bits From Left;
    print(result)


## CHECK EVEN OR ODD IN NUMBER;
def evenOrOdd(number=None) -> bool:
    dataType = type(number)
    if dataType == list:
        for num in number:
            if (num & 1):
                print(f"Num {num} is Odd")
            else:
                print(f"Num {num} is Even")
    elif dataType == int:
        if (number & 1):
            print(f"Num {number} is Odd")
        else:
            print(f"Num {number} is Even")
    else:
        return False

    return True


## FLIP ALL SET TO UNSET BIT;
def flipAllBits(num):
    return (~num)^num


## FLIP 32BIT INTEGER;
def flip32BitInterger(num):
    return (2**32-1)^num
Comment

PREVIOUS NEXT
Code Example
Python :: install quick-mailer 
Python :: how to write post method using flask 
Python :: read file into list python 
Python :: pandas select a row 
Python :: python telethon 
Python :: making a basic network scanner using python 
Python :: python get memory address 
Python :: numpy stack arrays vertically 
Python :: calculate the same value in list i python 
Python :: Plotly set axes labels 
Python :: discordpy get role by id 
Python :: /bin/sh: 1: python: not found 
Python :: python slice dictionary 
Python :: how to round an array in python 
Python :: number of unique pairs in columns pandas 
Python :: pandas bin columns 
Python :: how to send file in django response 
Python :: delete database entry using name django 
Python :: python tkinter colored line 
Python :: dictionary size in python 
Python :: loss funfction suited for softmax 
Python :: flask port 
Python :: print all attributes of object python 
Python :: how to import from parent directory 
Python :: how to get key of a particular value in dictionary python using index 
Python :: evaluate how much a python program memory 
Python :: how to round in python 
Python :: remove element from list 
Python :: dockerfile for django project 
Python :: how to merge two dictionaries in python 
ADD CONTENT
Topic
Content
Source link
Name
3+6 =