< Manipulación a nivel de bits />

← Python ⌂ Home

Operadores a nivel de bits

Usos

def is_even(x):
    return x & 1 == 0

>>> is_even(1)
False
>>> is_even(2)
True

def is_odd(x):
    return x & 1 == 1

>>> is_odd(1)
True
>>> is_odd(2)
False
def is_set(x, n):
    return True if(x & (1 << n)) else False

>>> bin(11)
'0b1011'
>>> is_set(11,0)
True
>>> is_set(11,1) 
True
>>> is_set(11,2)
False
>>> is_set(11,3)
True
def set(x, n):
    return x | (1 << n) 

>>> bin(11)
'0b1011'
>>> set(11,2)
15
>>> bin(15)
'0b1111'
def unset(x, n):
    return x & ~(1 << n)

>>> bin(11)
'0b1011'
>>> unset(11,0)
10
>>> bin(10)
'0b1010'
def toggle(x, n):
    return x ^ (1 << n)

>>> bin(11)
'0b1011'
>>> toggle(11,1)
9
>>> bin(9)
'0b1001'
>>> toggle(9,1)
11
def multiply_by_two(x):
    return x << 1

>>> multiply_by_two(2)
4
>>> multiply_by_two(10)
20
def divide_by_two(x):
    return x >> 1

>>> divide_by_two(20)
10
>>> divide_by_two(10)
5
def multiply_pow(x, n):
    return x << n

>>> multiply_pow(5,5)
160
>>> multiply_pow(5,1)
10
>>> multiply_pow(5,0)
5
>>> multiply_pow(5,1)
10
>>> multiply_pow(5,3)
40
def divide_pow(x,n):
    return x >> n 

>>> divide_pow(40,3)
5
>>> divide_pow(10,1)
5
>>> divide_pow(160,5)
5
>>> x = 10
>>> y = 11
>>> 
>>> x ^= y 
>>> y ^= x
>>> x ^= y
>>> 
>>> x
11
>>> y
10 
>>> x = 1
>>> -~x
2
>>> ~-x
0
def is_equal(x, y):
    return not x ^ y

>>> is_equal(1,1)
True
>>> is_equal(1,0)
False
def min(x, y):
    return y ^ ((x ^ y) & -(x < y))

def max(x, y):
    return x ^ ((x ^ y) & -(x < y))

>>> min(8,9)
8
>>> max(8,9)
9
def is_pow_two(x):
    return x & (x-1) == 0

>>> is_pow_two(1)
True
>>> is_pow_two(2)
True
>>> is_pow_two(3)
False
>>> is_pow_two(4)
True
>>> is_pow_two(5)
False
>>> is_pow_two(6)
False
>>> is_pow_two(7)
False
>>> is_pow_two(8)
True
def dec_to_bin(x):
    return str(x) if x <= 1 else binary(x >> 1) + str(x & 1)

>>> dec_to_bin(10)
'1010'

Recursos