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 :: docker run python 
Python :: staticmethod vs classmethod python 
Python :: merge sort python 
Python :: rank function in pandas 
Python :: python sys environment 
Python :: Display shape of the DataFrame 
Python :: installing intel-numpy 
Python :: looping over dictionary python 
Python :: what is tkinter in python 
Python :: python pathlib os module 
Python :: fonction nombre premier python 
Python :: qt designer python 
Python :: index.py:14: RuntimeWarning: invalid value encountered in true_divide return np.dot(user, user2) / (norm(user) * norm(user2)) 
Python :: logging python 
Python :: sleep your computer python 
Python :: 12 month movinf average in python for dataframe 
Python :: video timestamp opencv python 
Python :: how to add string in csv in python 
Python :: Insert between Characters Python 
Python :: Swap 2 items of a list in python 
Python :: write a python program to find the second largest number in a list 
Python :: authentication serializer drf 
Python :: django request.data 
Python :: retry on exception python 
Python :: split a pd dataframe 
Python :: pandas get tuples from dataframe 
Python :: gfg placement course 
Python :: true and false in python 
Python :: ssl socket python 
Python :: how to sort a list 
ADD CONTENT
Topic
Content
Source link
Name
5+4 =