Teaching my brother binary

I always find it helps to write the units at the top (works better on paper or with a monospaced font)

128|64|32|16|8|4|2|1

00000001 = 1 00000010 = 2 + 0 00000011 = 2 + 1 00000100 = 4 + 0 + 0 00000101 = 4 + 0 + 1 00000110 = 4 + 2 + 0 ... 01011001 = ?

0 + 64 + 0 + 16 + 8 + 0 + 0 + 1

working from the decimal number backwards too I start from the left, thinking of a random number 147

does the first number (128) fit? yes

so step 1: 128|64|32|16|8|4|2|1 10000000 = 128

so what does that leave? 19 right?

step 2: keep working down to the right, does the next number (64) fit into the remainder? no, does 32? no... 16 does though!

so

128|64|32|16|8|4|2|1 10000000 = 128 10010000 = 128 + 0 + 0 + 16 = 144

which leaves 3 remaining,

so step 3:

128|64|32|16|8|4|2|1 10000000 = 128 10010000 = 128 + 16 10010010 = 128 + 16 + 2 = 146

step 4:

128|64|32|16|8|4|2|1 10000000 = 128 10010000 = 128 + 16 10010010 = 128 + 16 + 2 10010011 = 128 + 16 + 2 + 1 = 147

Ok, we now know binary, but when is all this stuff actually used?

bonus irl example:

"chmod 644 [fileName]"

linux file permissions can be changed for User, members of the Group, and Others and those permissions can be read(r), write(w), execute(x), or no permission all, and you can do this for each type of user at a time, but that kinda sucks when you do this a lot, so luckily you can change them all at the same time using one command, chmod.

So in the above we're setting permission for all 3 types of people at the same time, and you can work out what permissions we're giving each type of people by converting to binary.

so take the first number 6, representing the user/owner of the file, so we have 3 states, ie 3 bits

r|w|x 4|2|1

so 6 in binary?

4 + 2 + 0

110

so the user has read and write ability, but can't execute the file, maybe you only want the admin to be able to execute files or something

next is 4, that's easy r|w|x 4|2|1 100

that's read only

so we have

user group others rwx rwx rwx 110 100 100 6 4 4

so irl you work from the permissions up, so it helps to know binary, eg to allow the owner to have all permissions, the group to have just read and write, and everyone else read only:

everything is 111 , rw is 110 and read only is 100, so that command would be chmod 764.

As an added bonus you technically just learned octal too, as you can see it's much easier to break it down into chunks that can be represented by a single digit than it is trying to work out the decimal for 111110100, and vice versa.

Hope that helps somebody.

/r/ProgrammerHumor Thread Link - i.redd.it