问题
I saw the following code in Bash shell Decimal to Binary conversion and I was wondering how it works? I tried googling with no avail.
D2B=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
echo ${D2B[7]}
What does the code above do?
回答1:
{N..M}
, for integer literals N and M, generates the series of integers from N to M, inclusively, separated by spaces. This is called a "brace expansion", and is a bashism. As you can see, all brace expansions are done before adding spaces between them.
variable=({some expansion})
puts each of the expanded items in an array, and ${variable[index number]}
extracts the value at that index. So your code effectively returns the number seven in binary string form.
回答2:
Just as an additional hint: This construct is fairly generic as it works for any n-based numbering system up to n = 9. Octal as an example:
$ D2O=({0..7}{0..7}{0..7}{0..7})
$ echo ${D2O[7]}
0007
$ echo ${D2O[8]}
0010
$ echo ${D2O[668]}
1234
$ echo ${D2O[4095]}
7777
The leading zeros can be eliminated in the same fashion as explained at Bash shell Decimal to Binary conversion:
echo $((10#${D2O[7]}))
7
来源:https://stackoverflow.com/questions/44738494/understanding-code-0-10-10-10-10-10-10-10-1