Speaking the native tongue

I’ve been interacting with computers for most of my life. I’ve been programming them for about the last 7-8 years. I figured I had a pretty good grasp of the language (no matter what you hear me screaming at computers, swearing isn’t actually their native language). This weekend I was reminded that computers don’t speak decimal. While it is easy and even natural to tell a computer to operate on decimal numbers, they really don’t like to do business that way. Case in point, division.

Say you want to convert meters to kilometers. Simple enough, take the number of meters you have and divide by 1000. For humans, we have a nifty shortcut for doing this…we just write the number down and move the decimal point three places to the left. No long division necessary. This is because we mentally picture/manipulate numbers in decimal (base 10). Each digit represents some power of 10. 1000 itself is a power of 10 (103), allowing you to perform the division by simply moving the decimal point three places to the left.

1234.0 meters = 1.234 kilometers

For computers, however, this isn’t nearly as simple. Computers look at the numbers in their binary form (base 2). That means each digit represents some power of 2. 1000 is not a power of 2, so you can’t do the quick decimal point swap-a-roo. You have to do the dreaded long division or repeated subtraction or whatever mechanism you (or your computer) prefer. Any way you slice it, you’ll never be as fast as you could be if you simply picked up the decimal point and moved it.

The nice thing is, you actually can pick up the decimal point and move it when working in binary…as long as you’re doing division by some power of 2. Say you want to divide by 16. Move the decimal point 4 places to the left (16 is 24). For example, divide eleven by two. Eleven in binary is 1011 and two is 10. As you can see, the decimal point just moves once to the left (because 2 is 21).

1011.0 / 10 = 101.1 (101.1 in decimal is 5.5)

So remember these things:

  1. When dividing by a number that is a power of the current base you’re working in, just shift the decimal point to the left. This works in any base (binary, decimal, octal, hexidecimal, etc).
  2. When performing math on a computer, remember that things that are easy for you because of your grasp of the decimal numbering system aren’t going to be easy for a computer, which only understands binary. If you can rework your code to do division and multiplication in base 2, you’ll be much better off.

In case you’re wondering why this came up, I’m working on an old problem where I was doing a bunch of very decimal centric operations on numbers. I shifted all that code to do things in a binary way and the speed improvement has been immense (not immense enough to make me rich yet, however).

Leave a Reply