repl.it
@21natzil/

Bit Manipulation

Python

A tutorial for teaching bit manipulation in python.

fork
loading
Files
  • main.py
  • docs.md
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def bin_print(first, second, op, result):
  print('  {:0>8}'.format(bin(first)[2:]))
  print(op + ' {:0>8}'.format(bin(second)[2:]))
  print('-' * 10)
  print('  {:0>8}'.format(bin(result)[2:]), end='\n\n')

# Bit manipulation is a great way to save values and compress data into it's smallest form possible. Not only does it have it's applications, it's also increadibly fun!
# Before we start, you need to be able to read binary. Once you've learned how (or already know how) to read binary, you can continue.
# Bit manipulation according to wikipedia is "is the act of algorithmically manipulating bits or other pieces of data shorter than a word.". At it's core, that's all it is. Just like math you preform opperations on binary numbers, opperations that you can't do in decimal!
# The first algorithm we're going over is the OR function. If either bits are 1, it will return 1. For example:

bin_print(23, 154, "|", 159)
#  00010111
#| 10011010
#----------
#  10011111

# As you can see, doing 1 | 0, you get 1. Doing 0 | 0, you get 0. Doing 1 | 1, you get 1. Very self-explanitory.
# Speaking of self-explanitory, the nex