Understanding code ({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})

≡放荡痞女 提交于 2019-12-06 06:31:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!