views:

1046

answers:

2

I am new in binary conversion. I use Python, Bash and AWK daily.

I would like to see binary conversion's applications in these languages. For example, I am interested in problems which you solve by it at your work.

Where do you use binary conversion in Python/Bash/AWK?

I would like to see examples of codes.

+1  A: 

Conversion of strings of binary digits to a number using Python on the commandline:

binary=00001111
DECIMAL=$(python -c "print int('$BINARY', 2)")
echo $decimal

See the docs for the int function.

Oh, wait, I misread the question, you want to know what converting to binary gets you. Well, that depends on what you mean by "convert to binary". Say I want to store a file with a million integers. The integers will be between 0 and 32,000. If I were to store them as text it would take at best two bytes for each number (single digit number and a separator), at worst six bytes (five digit number and a separator), with an average size of 4.6 bytes per number (see comment for the math). I also would have no easy way of choosing the 15th number. If I were store them as 16bit integers (in binary), every number would take up exactly two bytes and I could find the 15th number by seek'ing to offset 2*(15-1) and reading two bytes. Also, when I go to do math on the text based version I (or my language) must first convert the string to a number, whereas the binary version is already a 16bit number.

So, in short, you use binary types to

  1. save space
  2. have consistent record sizes
  3. speed up programs
Chas. Owens
@Owens: Do you use binary conversion daily?
Masi
Again, it depends on what you mean by "binary conversion". In some jobs many of the data files were binary files for the reasons listed above.
Chas. Owens
you have 10 1-digit, 90 2-digit, 900 3-digit, 9000 4-digit and 23000 5-digit numbers so your "average" is really 4.6
nosklo
+2  A: 

In shell, a nice use of dc:

echo 2i 00001111 pq | dc

2i means: base for input numbers is 2.

pq means: print and quit.

The other way is:

echo 2o 15 pq | dc

I don't remember having used this feature in real-world situations.

mouviciel
@mouviciel: One Winner of a Topcoder competition said to me that he have to use binary conversion daily with algorihtms. Can that be true?
Masi
Maybe for him... The rare occasions when I need to convert to and from binary is when I code close to the hardware.
mouviciel
No point in using echo and a pipe, save a process and just use dc -e '2i 00001111 pq'.
unwind