You are on page 1of 6

24.06.2020 г. bitwise-operators.

ipynb - Colaboratory

1234

1234

# 4 ones and 3 tens and 2 hundreds and 1 thousand

4*1 + 3*10 + 2*100 + 1*1000

1234

4*10**0 + 3*10**1 + 2*10**2 + 1*10**3

1234

0b1101

13

1*2**0 + 0*2**1 + 1*2**2 + 1*2**3

13

x = 0b11001011
y = 0b10101101

203

173

https://colab.research.google.com/drive/1HRmWEu_SRMH5C70IweNyWZSkI2hBZf97#printMode=true 1/6
24.06.2020 г. bitwise-operators.ipynb - Colaboratory
# bitwise AND -- use &
# if both of them are 1, we get 1

# x = 0b11001011
# y = 0b10101101

0b10001001

137

x & y

137

# bitwise OR -- use |
# if one of them is 1, then we get 1

# x = 0b11001011
# y = 0b10101101

0b11101111

239

x | y

239

# bitwise XOR -- use ^


# if one of them is 1, but not both, then we get 1

# x = 0b11001011
# y = 0b10101101

0b01100110

https://colab.research.google.com/drive/1HRmWEu_SRMH5C70IweNyWZSkI2hBZf97#printMode=true 2/6
24.06.2020 г. bitwise-operators.ipynb - Colaboratory

102
x ^ y

102

first_choice = True
second_choice = False
third_choice = True

choices = 0b101

choices & 0b100 # mask -- only let the first_choice bit through, if it's there at all

choices & 0b010 # is second_choice set? 2 if so, 0 if not

choices & 0b001 # is third_choice set? 1 if so, 0 if not

def foo():
print("Hello")

bin(foo.__code__.co_flags)

https://colab.research.google.com/drive/1HRmWEu_SRMH5C70IweNyWZSkI2hBZf97#printMode=true 3/6
24.06.2020 г. bitwise-operators.ipynb - Colaboratory

bin(x)

# bitwise NOT is (we think) ~ (tilde)

~x

~1234

~-1234

bin(x)

x << 1 # add a 0 to the end of the number

bin(406)

https://colab.research.google.com/drive/1HRmWEu_SRMH5C70IweNyWZSkI2hBZf97#printMode=true 4/6
24.06.2020 г. bitwise-operators.ipynb - Colaboratory

bin(x)

0b110010110

bin(x)

0b110010110

x << 4

0b110010110000

3248

x >> 2

50

203

bin(x)

https://colab.research.google.com/drive/1HRmWEu_SRMH5C70IweNyWZSkI2hBZf97#printMode=true 5/6
24.06.2020 г. bitwise-operators.ipynb - Colaboratory

'0b11001011'

0b110010

50

https://colab.research.google.com/drive/1HRmWEu_SRMH5C70IweNyWZSkI2hBZf97#printMode=true 6/6

You might also like