)%20%EC%9D%80%20%EC%A0%95%ED%99%95%ED%9E%88%20%EB%AC%B4%EC%97%87%EC%9D%84%20%ED%95%A9%EB%8B%88%EA%B9%8C%3F.png)
다음 bash 스크립트는 이진수가 주어지면 십진수를 표시합니다.
echo $((2#$1))
왜 정확히?
나는 그것이 $1
입력이라는 것을 이해합니다. 어쩌면 2
기본(바이너리)일 수도 있습니다. 하지만 사용된 구문을 이해할 수 없습니다.
답변1
남자 강타
echo [-neE] [arg ...]
Output the args, separated by spaces, followed by a newline.
The return status is 0 unless a write error occurs. If -n is
specified, the trailing newline is suppressed. If the -e option
is given, interpretation of the following backslash-escaped
characters is enabled.
[...]
Arithmetic Expansion
Arithmetic expansion allows the evaluation of an arithmetic expression
and the substitution of the result. The format for arithmetic expan‐
sion is:
$((expression))
[...]
Constants with a leading 0 are interpreted as octal numbers. A leading
0x or 0X denotes hexadecimal. Otherwise, numbers take the form
[base#]n, where the optional base is a decimal number between 2 and 64
representing the arithmetic base, and n is a number in that base. If
base# is omitted, then base 10 is used. When specifying n, the digits
greater than 9 are represented by the lowercase letters, the uppercase
letters, @, and _, in that order. If base is less than or equal to 36,
lowercase and uppercase letters may be used interchangeably to repre‐
sent numbers between 10 and 35.
답변2
다음 문서에서:https://tiswww.case.edu/php/chet/bash/bashref.html#Shell-Arithmetic
앞에 0이 붙은 상수는 8진수로 해석됩니다. 앞에 '0x' 또는 '0X'가 있으면 16진수를 나타냅니다. 그렇지 않은 경우 숫자는 [base#]n 형식을 취합니다. 여기서 선택적 기수는 산술 기수를 나타내는 2에서 64 사이의 십진수이고 n은 해당 기수의 숫자입니다. base#을 생략하면 base 10이 사용됩니다. n을 지정할 때 9보다 큰 숫자는 소문자, 대문자, '@', '_'의 순서로 표시됩니다. 밑수가 36보다 작거나 같으면 소문자와 대문자를 번갈아 사용하여 10에서 35 사이의 숫자를 나타낼 수 있습니다.
그래서 echo $((16#FF))
출력 255
과 echo $((2#0110))
출력6
답변3
이포르의 답변훌륭하지만 아주 약간 불완전합니다. Bash 매뉴얼 페이지의 인용된 부분에는 구문이 상수에 대해서만 작동하고 상수가 아니라고 명시되어 있습니다. 이게 어떻게 되는지 물어봐야 해[base#]n
2#$1
정말공장!
확장
확장은 단어로 분할된 후 명령줄에서 수행됩니다. 수행되는 확장에는 중괄호 확장, 물결표 확장, 매개변수 및 변수 확장, 명령 대체, 산술 확장, 단어 분할, 경로 이름 확장 등 7가지 종류가 수행됩니다.
확장 순서는 다음과 같습니다: 중괄호 확장; 물결표 확장, 매개변수 및 변수 확장, 산술 확장 및 명령 대체(왼쪽에서 오른쪽으로 수행됨) 단어 분리; 및 경로 이름 확장.
기본적으로 Bash는 변수 대체를 먼저 수행하므로 $1
먼저 해당 값으로 대체됩니다. 그런 다음에야 적절한 상수만 보는 산술 확장을 수행합니다.