Short notes on mathematics and programming
Binary numeral system
Cheat sheet
✍️ A number can be written in binary form
✍️ Wikipedia: binary numeral system
Lecture
In one of the previous notes we discussed how to solve "swap two values with three variables" using XOR. Here we take a step back and explain what is happening. Let’s start with binary representation of numbers.
For details on positional base-2 notation, see Wikipedia. The key points:
✍️ Any integer can be written as a sequence of 0 and 1
✍️ You can convert binary representation to decimal and back
To convert binary to decimal, sum bits with weights (right to left): 1, 2, 4, 8, 16, .... Examples: 101 = 1×4 + 0×2 + 1×1 = 5; 011 = 0×4 + 1×2 + 1×1 = 3.
For 3-bit numbers:000 -> 0001 -> 1010 -> 2011 -> 3100 -> 4101 -> 5110 -> 6111 -> 7
To convert from decimal to binary, find the number in the right column and take the corresponding representation on the left.
In the next posts, using this table, we will look at how XOR works and which property allows it to swap two values without introducing a third variable.
#education #devTopic #junior
