Weekly Algo: A bit about bits

Emiko N-P.
3 min readNov 13, 2021

--

For this week’s weekly algo, I am going to talk about bits and bit manipulation. Although this is not an algorithm within itself, understand what bits are and how to handle them is very important to understanding other techniques.

So, what are bits? Underneath all our programming languages and applications and interfaces, at the very base of everything are strings of ones and zeros. These strings of numbers are called binary code. We call the individual ones and zeros bits.

Photo by Alexander Sinn on Unsplash

We can represent lots of data using bits. For example, let’s take the number 25. To represent this number in bits we would write: 11001. Those five digits each represent a power of two going from right to left. To figure out what number is represented by a series of bits, we start from the right and multiply each binary digit by its corresponding power of 2. Doing this for our example of 25, we get: 1*20 + 0*21 + 0*22 + 1*23 + 1*24. Substituting in the values each power of 2, that looks like 1*1 + 0*2 + 0*4 + 1*8 + 1*16 = 1 + 8 + 16 = 9 + 16 = 25. Another way to think of this is that the bits for 25 are the remainder after dividing by two of each successive number going from right to left i.e. 25/2 = 12 r 1, 12/2 = 6 r0, 6/2 = 3 r2, 3/2 = 1 r1, ½ = 0 r1, so remainders from right to left are 11001. In many coding languages including JavaScript, Python and others, numbers are encoding using 64bits, so for our example of 25 we would have 11001 followed by 59 zeros to make up a string of 64 bits. This lets those languages keep track of numbers that are very big or have long decimals.

JavaScript also comes with some very handy operators to manipulate bits, these are called bitwise opperator. We will go into usages for these in more depth next week, but for now here is a list of each operator:

AND (&) : if bitA AND bitB are 1, they will both be set to 1

OR (|) : if bitA OR bitB are 1, they will both be set to 1

NOT(~) : changes all bits to their opposite values (all 1s to 0s and 0s to 1s)

XOR(^) : if either or both bitA and bitB are 1, sets both bits to 1

Left Shift (<<) : shifts all bits left one slot

Right Shift (>>) : shifts all bits right one slot

By using bit manipulation, we can do all sorts of interesting things and solve some tricky problems. We’ll go into exactly how to do all that next week, but for now it’s important to know that bits are the base language the computer speaks, and so learning to handle them is fundamentally important to understanding computers and how to control them to create applications, programs, and much more.

I’m also attaching some resources bellow for you to explore and learn more about bits and bit manipulation.

--

--

Emiko N-P.
Emiko N-P.

Written by Emiko N-P.

0 Followers

Hello, my name is Emiko. I am an aspiring Software Engineer and student at Flatiron School.

No responses yet