Develop­ment

Back to Basics: Arrays & Bitwise Operators

Back to Basics: Arrays & Bitwise Operators

This post is going back to the basics. When I used to program in C and C++, it was common to see code using bitwise operators. These operations are a great method for storing information concisely and efficiently. (Wikipedia has a helpful overview, if you’re interested.)

With the abundance of memory and disk space today, conciseness and efficiency aren’t always at the top of a developer’s concerns. I haven’t seen or used many bitwise operations lately. That is, of course, until I needed a simple and clean solution to a problem.

This post will cover the basics of & and | bitwise operators.

Assume you have two arrays:

  a = [1, 2, 3, 4] # => [1, 2, 3, 4]
  b = [3, 4, 5, 6] # => [3, 4, 5, 6]

You’ve been asked to find the intersection between the two arrays. You could iterate through both arrays and append the matching elements to a new array.

  intersection = []
  a.each { |e| b.include?(e) ? (intersection << e) : intersection } # => [1, 2, 3, 4]

  intersection # => [3, 4]

That code gets the job done. However, a much more concise way of accomplishing this task would be to use the & operator.

  a & b # => [3, 4]

Now instead of the intersection, say you were asked for the union of the two arrays. This could be achieved with the following code.

  (a + b).uniq # => [1, 2, 3, 4, 5, 6]

Or, you could employ a bitwise operator.

  a | b # => [1, 2, 3, 4, 5, 6]

As you can see, bitwise operators can help you solve basic problems concisely. Interestingly, these examples of operations on arrays are not necessarily more efficient. In my next post, I’ll dig deeper into this subject.

pin-icon phone