What are bitwise shift (bit-shift) operators and how do they work?

后端 未结 11 1434
生来不讨喜
生来不讨喜 2020-11-21 04:46

I\'ve been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators) ...

What I\'m wondering

11条回答
  •  孤街浪徒
    2020-11-21 04:48

    Some useful bit operations/manipulations in Python.

    I implemented Ravi Prakash's answer in Python.

    # Basic bit operations
    # Integer to binary
    print(bin(10))
    
    # Binary to integer
    print(int('1010', 2))
    
    # Multiplying x with 2 .... x**2 == x << 1
    print(200 << 1)
    
    # Dividing x with 2 .... x/2 == x >> 1
    print(200 >> 1)
    
    # Modulo x with 2 .... x % 2 == x & 1
    if 20 & 1 == 0:
        print("20 is a even number")
    
    # Check if n is power of 2: check !(n & (n-1))
    print(not(33 & (33-1)))
    
    # Getting xth bit of n: (n >> x) & 1
    print((10 >> 2) & 1) # Bin of 10 == 1010 and second bit is 0
    
    # Toggle nth bit of x : x^(1 << n)
    # take bin(10) == 1010 and toggling second bit in bin(10) we get 1110 === bin(14)
    print(10^(1 << 2))
    

提交回复
热议问题