Bitwise operation and usage

Viewed 150390

Consider this code:

x = 1        # 0001
x << 2       # Shift left 2 bits: 0100
# Result: 4

x | 2        # Bitwise OR: 0011
# Result: 3

x & 1        # Bitwise AND: 0001
# Result: 1

I can understand the arithmetic operators in Python (and other languages), but I never understood 'bitwise' operators quite well. In the above example (from a Python book), I understand the left-shift but not the other two.

Also, what are bitwise operators actually used for? I'd appreciate some examples.

18 Answers

Sets

Sets can be combined using mathematical operations.

  • The union operator | combines two sets to form a new one containing items in either.
  • The intersection operator & gets items only in both.
  • The difference operator - gets items in the first set but not in the second.
  • The symmetric difference operator ^ gets items in either set, but not both.

Try It Yourself:

first = {1, 2, 3, 4, 5, 6}
second = {4, 5, 6, 7, 8, 9}

print(first | second)

print(first & second)

print(first - second)

print(second - first)

print(first ^ second)

Result:

{1, 2, 3, 4, 5, 6, 7, 8, 9}

{4, 5, 6}

{1, 2, 3}

{8, 9, 7}

{1, 2, 3, 7, 8, 9}

To flip bits (i.e. 1's complement/invert) you can do the following:

Since value ExORed with all 1s results into inversion, for a given bit width you can use ExOR to invert them.

In Binary
a=1010 --> this is 0xA or decimal 10
then 
c = 1111 ^ a = 0101 --> this is 0xF or decimal 15
-----------------
In Python
a=10
b=15
c = a ^ b --> 0101
print(bin(c)) # gives '0b101'

You can use bit masking to convert binary to decimal;

int a = 1 << 7;
int c = 55;
for(int i = 0; i < 8; i++){
    System.out.print((a & c) >> 7);     
    c = c << 1;
}

this is for 8 digits you can also do for further more.

Bit manipulation, in some cases, can obviate or reduce the need to loop over a data structure and can give many-fold speed-ups, as bit manipulations are processed in parallel, but the code can become more difficult to write and maintain.

1.Check the integer is even or odd.

def even_or_odd(num):                                   
    if (num & 1) == 0:                                               
        return f"{num} is even number"                          
    else:                                                        
        return f"{num} is odd number"
 

2.Multiply by 2 using the left shift operator:

print(7 << 1)                     
    output: 14  



 

3.Divide 2 using the right shift operator:

print(14 >> 1)              
 output: 7   

4.One’s complement operator (~): If we want to invert every bit of a number i.e change bit ‘0’ to ‘1’ and bit ‘1’ to ‘0’.

num = 7
print(~num)                     
output: -8 

5.Two’s complement of the number:

num = 5                                                                            

twos_complement = -num                                                          

print(f"This is two's complement {twos_complement}")                            

print(f"This is also two's complement {~num + 1}")   

6.Upper case English alphabet to lower case: ch |= ' '
This mask is bit representation of space character (‘ ‘).

ch = ‘A’        #(01000001)         
mask = ‘ ‘      #(00100000)     
ch | mask = ‘a’ #(01100001) 

7.Lower case English alphabet to upper case: ch &= '
This mask is a bit representation of the underscore character (‘
‘). The character ‘ch’ then AND with mask.

ch = ‘a’             #(01100001)     
mask = ‘_ ‘          #(11011111)           
ch & mask = ‘A’      #(01000001) 

8.A number is a power of 2.

  x and (not(x & (x - 1)))

9.The Quickest way to swap two numbers.

 a = a ^ b

10.Count set bits in an integer.

def  countSetBits(n):                                      

    count = 0                                              

    while (n):                                               

        count += n & 1                                               

        n >>= 1                     

    return count  

Maybe you can use bin() function.

print(bin(15).count('1'))
# output 4

Brian Kernighan’s Algorithm: If we do n & (n-1) in a loop and count the number of times the loop executes, we get the set bit count.

def countSetBits(n):                                                 

    count = 0                                                       

    while (n):                                                       

        n &= (n-1)                                                   

        count += 1                                                                       

    return count   

11.Count unset bits of a number.

def countunsetbits(n):                                                    

    count = 0                                                                                            



    x = 1                                                                                       

    while(x < n + 1):                                                   

        if ((x & n) == 0):                                 

            count += 1                                              

        x = x << 1                                                   

    return count   
  1. Toggle all bits after the most significant bit

    def toggle(n):

    temp = 1                                                                              
    
    while (temp <= n):                                                                            
    
        n = n ^ temp                                              
    
    
        temp = temp << 1                                     
    return n  
    
Related