[one-liner]: Command Line Calculator – bc – Example

Background

I was recently listening to the podcast Security Now! episode #316. In this episode Steve Gibson discussed his Off the Grid paper based password system, where he mentioned the number 9.337 × 10426. This number represents the total number of 26×26 Latin Squares.

Excerpt from grc.com’s Off The Grid details page…

This number, expressed in scientific notation, is: 9.337 × 10426 and the log(2) (logarithm base 2) is approximately 1418. This means that a binary number having at least 1418 bits (because this is the known lower bound) would be required to specify one of the 26×26 Latin Squares possible.

The last comment of 1418 bits interested me and I was wondering how he calculated it. Here’s one way to do it using the command line utility bc, aka. bench calculator.

Solution

But first some math! In order to calculate the “size” of a number, such as 100, you can use the math function common logarithm. Common log assumes you’re calculating the log with respect to base 10 (log 10 (x)). Other logs such as binary log are calculated against base 2 (log 2 (x)). So the common log, log 10 (100) = 2. The 2 represents the power you’d have to raise the base (10) to in order to calculate the original number (100), i.e. 102 = 100.

Excerpt from wikipedia…

The logarithm of a number is the exponent by which a fixed number, the base, has to be raised to produce that number.

You can calculate the binary log of 100 like so: log 10 (100)/log 10 (2). This equals 6.64385618977. To check it calculate 26.64385618977 = 100. See it worked. One nice side effect to using this calculation is that it essentially tells you the number of binary bits needed to represent a given number. So in our example (100), we’d need 6 bits to represent (100) in binary.

  • 26 = 64
  • 25 = 32
  • 22 = 4

Equals 64 + 32 + 4 = 100, and can be written thusly: 110010 2.

OK, so now that we have some background what does any of this have to do with the Security Now! podcast and using the command line tool bc? Here’s the point!

I tried to use my GUI calculator, galculator to calculate log 2 (9.337 × 10426), however this number proved too large and resulted in inf. So I next turned to the command line tool bc. The following command is how I did it:

1
2
% echo "l(9.337*10^426)/l(2)"|bc -l
1418.36432750510331443454

l(x) is the log function within bc. Above I’m calculating the log 10 (9.337*10426) and dividing it by the log 10 (2). The -l switch to bc is necessary to enable the family of math functions which includes log.

And there you have it, a long winded explanation of how to calculate the number of binary bits needed to represent a number using bc!

References

links
local copies

NOTE: For further details regarding my one-liner blog posts, check out my one-liner style guide primer.

This entry was posted in bc, linux, one-liner, Security, Syndicated, tips & tricks. Bookmark the permalink.

Comments are closed.