How to Convert a Binary String to an Integer in Ruby
The weather is changing outside, the days are getting shorter and colder and there are a shocking number of colored string lights hanging around my neighborhood. For many, these are all signs of Christmas being around the corner. For programmers, these are signs that Advent of Code is back.
For readers unfamiliar with AoC, Advent of Code is a programming challenge based advent calendar in which each day brings a new programming question. If you are familiar with LeetCode or HackerRank then you’ve definitely dealt with these type of questions. Where Advent of Code is different is that it pairs the sets of questions with a very fun and quirky story.
I have really been enjoying Advent of Code this year as it offers an avenue to stretch your mind in ways some routine maintenance tickets may not. One of the early days focused on calculating products based off an input of binary strings. While I was familiar with binary numbers, building a helper method to convert from binary strings to integers seemed like a good topic to go in depth on and share.
What are Binary Numbers and How to Interpret Them
Before we can understand what Binary Numbers are, we need to understand how numbers are expressed. Numbers are expressed using numeral systems. Though this term may sound foreign, we are all very familiar with the base-10 numeral system which uses the characters { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } to represent all the numbers in our daily lives.
With these numbers (numerals) we can create an infinite number of values that may represent how many donuts we ate this morning or the fractions of a cent of tax charged for our third cup of coffee.
Binary numbers are just another way to express numbers and are very common for computing purposes. Binary numbers are formed using the base-2 numeral system that consists of { 0, 1 }. Though strange to think about, this 2 character system can be just as expressive as the 10 character base-10 system. Here is a list of base-10 values and their corresponding base-2 representations:
How in the world is 9 the same as ‘1001’, you may be asking yourself. Let’s take a look at how we calculate base-10 number values with base-2 values. The first thing to understand when working with binary numbers is that unlike English, we read binary numbers right to left. If we want to understand how much our binary string is worth, we need to start with the right most digit and examine its value before moving along each preceding digit to calculate our integer. How do we transform binary to base-10? Let’s talk about what our string of 1’s and 0’s really represent.
These strings are really a set of instructions of how to construct the sum of values that will yield our final integer. There’s a lot to that statement so let’s take it piece by piece. First, what do I mean by sum of values? For binary strings, each 1 and 0 corresponds to a calculated value that when added or summed together will give us an integer.
The 1’s and 0’s are instructions to either include or exclude the value in the given position. What are the values in each position? To understand what the value of each of our 1’s and 0’s is, let’s look at the following equation:
This equation is all the information we need to calculate the values of each of our integers. The bit here represents either the 1 or 0 of our string. The index corresponds to the position in the string (right to left) of each of our 1’s and 0’s. To see this in action let’s calculate our binary string for representing 9, ‘1001.’
Here we see the string broken down according to our formula. Reading from right to left, we have a 1 in the first position (index 0) and fourth position (index 3). Inputting these values for each of those yields a 1 + 8 which gives us 9. By carefully translating your values from string to this equation you can quickly convert any binary string to an integer!
How to use Ruby to Convert Binary Strings
Now that we have an understanding of what binary numbers are and how to translate them to integers, how will we use Ruby to turn them into integers? This part shouldn’t be too hard with a good understanding of the last section.
A very helpful trick for converting binary strings to integers in code is to invert the string before using it for calculating. Sure, you could use a decrementing for loop to loop backwards, but KISS hasn’t failed me yet!
After that it’s a simple matter of translating our string’s characters and indices to get the final result:
See, not too bad!
Final Thoughts
I hope that you now have a good understanding of what binary numbers are and how to convert a binary string into an integer in Ruby. I’ve always been a proponent of you can read it, but you don’t know it until you’ve done it. If you’d like a fun opportunity to roll up your sleeves and get your hands dirty with some fun code challenges then please check out Advent of Code (https://adventofcode.com/). The questions are difficult, but I promise if you are able to answer them then you will have learned a lot and be a much better developer!
Notes