2

When converting decimal values to their binary representation, it is possible to use the following commands:

val=12
D2B=({0..1}{0..1}{0..1}{0..1}{0..1})
echo ${D2B[$val]}

While this works, I am unable to understand or find why it does so. Would be great if someone could explain it or point me to a resource that does.

  • 4
    HINT: what does echo {0..1}{0..1}{0..1}{0..1}{0..1} output? – steeldriver May 12 '15 at 17:55
  • @iyiyy: It would be nice if you link to source of your code. – Cyrus May 12 '15 at 20:52
3

Brace expansion in form {x..y} give you all possible characters from range x to y. In this case, {0..1} give you 0 and 1. Combine two pieces give you 2^2 four possible values:

$ printf %s\\n {0..1}{0..1}
00
01
10
11

Combine five pieces give you 2^5 thirty two possible values from 0 to 32 in binary form:

$ printf %s\\n {0..1}{0..1}{0..1}{0..1}{0..1}
00000
00001
00010
00011
00100
00101
00110
00111
01000
01001
01010
01011
01100
.....
11110
11111

Saving all values in D2B array, with decimal index corresponding to it binary value. Accessing index 12 ${D2B[$val]} gave you the binary value of 12 decimal.

Actually, you can make it shorter with {x,y}:

D2B=({0,1}{0,1}{0,1}{0,1}{0,1})
2

First, note that this is quite a memory inefficient way to do this. You might, instead, consider the answers on this question.


As for your question, though...

D2B=({0..1}{0..1}{0..1}{0..1}{0..1})

This line creates an array called D2B that contains all possible binary values from 00000 to 11111. Brace expansions work like this:

% printf '%s %s %s\n' {0..2}{0..2}{0..2} 
000 001 002
010 011 012
020 021 022
100 101 102
110 111 112
120 121 122
200 201 202
210 211 212
220 221 222

Due to the fact that brace expansions are expanded from the first to the last when they are adjoined, the array looks something like this:

00000 00001 00010 .... 11101 11110 11111

The indexes of these values correspond to the binary values contained within them, since here, brace expansions and the mathematic representations of numbers use the same rules.

As such, index 0 is 00000, index 5 is 00101, and so on. Since you pass $val as the index to use, the binary corresponding to your value is echoed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.