How do you use Binary conversion in Python/Bash/AWK?

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.

Upvotes: 1

Views: 2610

Answers (3)

2rs2ts
2rs2ts

Reputation: 11066

In newer versions of Python there exists the bin() function which I believe takes an int and returns a binary literal, of form 0b011010 or whatever.

Upvotes: 0

Chas. Owens
Chas. Owens

Reputation: 64939

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

Upvotes: 3

mouviciel
mouviciel

Reputation: 67869

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.

Upvotes: 2

Related Questions