> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-fix-nav-issues.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> 인코딩 함수에 대한 문서

# 인코딩 함수

{/*AUTOGENERATED_START*/}

<div id="bech32Decode">
  ## bech32Decode
</div>

도입 버전: v25.6.0

bech32 또는 bech32m 알고리즘으로 생성된 Bech32 주소 문자열을 디코딩합니다.

<Note>
  인코딩 함수와 달리 `bech32Decode`는 패딩된 FixedStrings도 자동으로 처리합니다.
</Note>

**구문**

```sql theme={null}
bech32Decode(address[, 'raw'])
```

**인수**

* `address` — 디코딩할 Bech32 문자열입니다. [`String`](/ko/reference/data-types/string) 또는 [`FixedString`](/ko/reference/data-types/fixedstring)
* `mode` — 선택 사항입니다. 첫 번째 바이트를 witness version으로 제거하지 않고 디코딩하려면 `'raw'`를 지정합니다. SegWit이 아닌 주소(예: Cosmos SDK)에 사용하십시오. [`String`](/ko/reference/data-types/string)

**반환 값**

문자열을 인코딩하는 데 사용된 `(hrp, data)`로 이루어진 튜플을 반환합니다. 데이터는 바이너리 형식입니다. [`Tuple(String, String)`](/ko/reference/data-types/tuple)

**예시**

**주소 디코딩**

```sql title=Query theme={null}
SELECT tup.1 AS hrp, hex(tup.2) AS data FROM (SELECT bech32Decode('bc1w508d6qejxtdg4y5r3zarvary0c5xw7kj7gz7z') AS tup)
```

```response title=Response theme={null}
bc   751E76E8199196D454941C45D1B3A323F1433BD6
```

**테스트넷 주소**

```sql title=Query theme={null}
SELECT tup.1 AS hrp, hex(tup.2) AS data FROM (SELECT bech32Decode('tb1w508d6qejxtdg4y5r3zarvary0c5xw7kzp034v') AS tup)
```

```response title=Response theme={null}
tb   751E76E8199196D454941C45D1B3A323F1433BD6
```

<div id="bech32Encode">
  ## bech32Encode
</div>

도입 버전: v25.6.0

[Bech32 or Bech32m](https://en.bitcoin.it/wiki/Bech32) 알고리즘을 사용하여 사람이 읽을 수 있는 부분(HRP)과 함께 바이너리 데이터 문자열을 인코딩합니다.

<Note>
  [`FixedString`](/ko/reference/data-types/fixedstring) 데이터 타입을 사용할 때 값이 행을 완전히 채우지 않으면 null 문자로 패딩됩니다.
  `bech32Encode` 함수는 hrp 인수에 대해서는 이를 자동으로 처리하지만, data 인수는 값이 패딩되지 않아야 합니다.
  따라서 모든 값의 길이가 같고 `FixedString` 컬럼도 해당 길이로 설정되어 있다고 확신할 수 있는 경우가 아니라면, 데이터 값에 [`FixedString`](/ko/reference/data-types/fixedstring) 데이터 타입을 사용하지 않는 것이 좋습니다.
</Note>

**구문**

```sql theme={null}
bech32Encode(hrp, data[, witver | 'bech32' | 'bech32m'])
```

**인수**

* `hrp` — 코드의 "human-readable part"를 지정하는 `1 - 83`자의 소문자 `String`입니다. 일반적으로 'bc' 또는 'tb'입니다. [`String`](/ko/reference/data-types/string) 또는 [`FixedString`](/ko/reference/data-types/fixedstring)
* `data` — 인코딩할 바이너리 데이터 `String`입니다. [`String`](/ko/reference/data-types/string) 또는 [`FixedString`](/ko/reference/data-types/fixedstring)
* `witver_or_variant` — 선택 사항입니다. UInt\* witness version(기본값 = 1, Bech32는 `0`, Bech32m은 `1`+) 또는 `String` 인코딩 variant(`'bech32'` (BIP173) 또는 `'bech32m'` (BIP350)) 중 하나입니다. 문자열 variant를 사용하면 witness version 바이트를 앞에 붙이지 않습니다. 이는 Cosmos SDK와 같은 비-SegWit 주소에 필요합니다. [`UInt*`](/ko/reference/data-types/int-uint) 또는 [`String`](/ko/reference/data-types/string)

**반환 값**

human-readable part, 항상 '1'인 구분 문자, 그리고 data part로 구성된 Bech32 주소 문자열을 반환합니다. 문자열 길이는 90자를 초과하지 않습니다. 알고리즘이 입력으로 유효한 주소를 생성할 수 없으면 빈 문자열을 반환합니다. [`String`](/ko/reference/data-types/string)

**예시**

**기본 Bech32m**

```sql title=Query theme={null}
-- witness version을 지정하지 않으면 기본값은 1이며, 업데이트된 Bech32m 알고리즘이 사용됩니다.
SELECT bech32Encode('bc', unhex('751e76e8199196d454941c45d1b3a323f1433bd6'))
```

```response title=Response theme={null}
bc1w508d6qejxtdg4y5r3zarvary0c5xw7k8zcwmq
```

**Bech32 알고리즘**

```sql title=Query theme={null}
-- witness version이 0이면 다른 주소 문자열이 반환됩니다.
SELECT bech32Encode('bc', unhex('751e76e8199196d454941c45d1b3a323f1433bd6'), 0)
```

```response title=Response theme={null}
bc1w508d6qejxtdg4y5r3zarvary0c5xw7kj7gz7z
```

**사용자 지정 HRP**

```sql title=Query theme={null}
-- 'bc' (메인넷)와 'tb' (테스트넷)는 SegWit 주소 형식에서 허용되는 유일한 hrp 값이지만,
-- Bech32는 위의 요구 사항을 충족하는 모든 hrp를 허용합니다.
SELECT bech32Encode('abcdefg', unhex('751e76e8199196d454941c45d1b3a323f1433bd6'), 10)
```

```response title=Response theme={null}
abcdefg1w508d6qejxtdg4y5r3zarvary0c5xw7k9rp8r4
```

**Cosmos SDK 주소 (BIP173, witness version 없음)**

```sql title=Query theme={null}
-- 'bech32' 변형을 사용하면 witness version 바이트 없이 원시 데이터를 인코딩하며,
-- Cosmos SDK, Injective, Osmosis 및 기타 non-SegWit 체인과 호환됩니다.
SELECT bech32Encode('inj', unhex('751e76e8199196d454941c45d1b3a323f1433bd6'), 'bech32')
```

```response title=Response theme={null}
inj1w508d6qejxtdg4y5r3zarvary0c5xw7kgj5aqs
```

<div id="bin">
  ## bin
</div>

도입 버전: v21.8.0

서로 다른 타입에 대해 다음 로직에 따라 인수의 이진 표현을 포함하는 문자열을 반환합니다:

| 유형                         | 설명                                                                                                                                   |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `(U)Int*`                  | 최상위 비트부터 최하위 비트까지(빅 엔디언 또는 "사람이 읽기 쉬운" 순서) 2진수 자릿수를 출력합니다. 가장 앞의 0이 아닌 바이트부터 시작하며(선행 0 바이트는 생략), 선행 자릿수가 0이더라도 각 바이트는 항상 8자리로 출력합니다. |
| `Date` and `DateTime`      | 해당하는 정수 형태로 포맷됩니다(`Date`는 epoch 이후의 일 수, `DateTime`는 Unix timestamp 값).                                                              |
| `String` and `FixedString` | 모든 바이트는 각각 8자리 이진수로 그대로 인코딩됩니다. 0 바이트도 생략되지 않습니다.                                                                                    |
| `Float*` and `Decimal`     | 메모리상의 표현으로 인코딩됩니다. 리틀 엔디언 아키텍처를 지원하므로 리틀 엔디언으로 인코딩됩니다. 앞뒤의 0 바이트도 생략되지 않습니다.                                                         |
| `UUID`                     | 빅 엔디언 순서의 문자열로 인코딩됩니다.                                                                                                               |

**구문**

```sql theme={null}
bin(arg)
```

**인수**

* `arg` — 이진 표현으로 변환할 값입니다. [`String`](/ko/reference/data-types/string) 또는 [`FixedString`](/ko/reference/data-types/fixedstring) 또는 [`(U)Int*`](/ko/reference/data-types/int-uint) 또는 [`Float*`](/ko/reference/data-types/float) 또는 [`Decimal`](/ko/reference/data-types/decimal) 또는 [`Date`](/ko/reference/data-types/date) 또는 [`DateTime`](/ko/reference/data-types/datetime)

**반환 값**

인수의 이진 표현을 담은 문자열을 반환합니다. [`String`](/ko/reference/data-types/string)

**예시**

**간단한 정수**

```sql title=Query theme={null}
SELECT bin(14)
```

```response title=Response theme={null}
┌─bin(14)──┐
│ 00001110 │
└──────────┘
```

**Float32 값**

```sql title=Query theme={null}
SELECT bin(toFloat32(number)) AS bin_presentation FROM numbers(15, 2)
```

```response title=Response theme={null}
┌─bin_presentation─────────────────┐
│ 00000000000000000111000001000001 │
│ 00000000000000001000000001000001 │
└──────────────────────────────────┘
```

**Float64 수**

```sql title=Query theme={null}
SELECT bin(toFloat64(number)) AS bin_presentation FROM numbers(15, 2)
```

```response title=Response theme={null}
┌─bin_presentation─────────────────────────────────────────────────┐
│ 0000000000000000000000000000000000000000000000000010111001000000 │
│ 0000000000000000000000000000000000000000000000000011000001000000 │
└──────────────────────────────────────────────────────────────────┘
```

**UUID 변환**

```sql title=Query theme={null}
SELECT bin(toUUID('61f0c404-5cb3-11e7-907b-a6006ad3dba0')) AS bin_uuid
```

```response title=Response theme={null}
┌─bin_uuid─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ 01100001111100001100010000000100010111001011001100010001111001111001000001111011101001100000000001101010110100111101101110100000 │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
```

<div id="bitPositionsToArray">
  ## bitPositionsToArray
</div>

도입 버전: v21.7.0

이 함수는 부호 없는 정수의 이진 표현에서 값이 1인 비트의 위치를 오름차순으로 반환합니다.
부호 있는 입력 정수는 먼저 부호 없는 정수로 변환됩니다.

**구문**

```sql theme={null}
bitPositionsToArray(arg)
```

**인수**

* `arg` — 정수 값입니다. [`(U)Int*`](/ko/reference/data-types/int-uint)

**반환 값**

입력값의 이진 표현에서 1인 비트의 위치를 오름차순으로 정렬한 배열을 반환합니다. [`Array(UInt64)`](/ko/reference/data-types/array)

**예시**

**단일 비트만 설정된 경우**

```sql title=Query theme={null}
SELECT bitPositionsToArray(toInt8(1)) AS bit_positions
```

```response title=Response theme={null}
┌─bit_positions─┐
│ [0]           │
└───────────────┘
```

**모든 비트가 설정된 상태**

```sql title=Query theme={null}
SELECT bitPositionsToArray(toInt8(-1)) AS bit_positions
```

```response title=Response theme={null}
┌─bit_positions─────────────┐
│ [0, 1, 2, 3, 4, 5, 6, 7]  │
└───────────────────────────┘
```

<div id="bitmaskToArray">
  ## bitmaskToArray
</div>

도입 버전: v1.1.0

이 함수는 정수를 2의 거듭제곱의 합으로 분해합니다.
각 2의 거듭제곱은 오름차순으로 정렬된 배열로 반환됩니다.

**구문**

```sql theme={null}
bitmaskToArray(num)
```

**인수**

* `num` — 정수 값입니다. [`(U)Int*`](/ko/reference/data-types/int-uint)

**반환 값**

입력된 숫자를 합으로 하는 2의 거듭제곱들을 오름차순으로 정렬한 배열을 반환합니다. [`Array(UInt64)`](/ko/reference/data-types/array)

**예시**

**기본 예시**

```sql title=Query theme={null}
SELECT bitmaskToArray(50) AS powers_of_two
```

```response title=Response theme={null}
┌─powers_of_two───┐
│ [2, 16, 32]     │
└─────────────────┘
```

**단일 2의 거듭제곱**

```sql title=Query theme={null}
SELECT bitmaskToArray(8) AS powers_of_two
```

```response title=Response theme={null}
┌─powers_of_two─┐
│ [8]           │
└───────────────┘
```

<div id="bitmaskToList">
  ## bitmaskToList
</div>

v1.1.0에서 도입됨

`bitmaskToArray`와 비슷하지만, 2의 거듭제곱을 쉼표로 구분한 문자열로 반환합니다.

**구문**

```sql theme={null}
bitmaskToList(num)
```

**인수**

* `num` — 정수 값입니다. [`(U)Int*`](/ko/reference/data-types/int-uint)

**반환 값**

쉼표로 구분된 2의 거듭제곱 값이 포함된 문자열을 반환합니다. [`String`](/ko/reference/data-types/string)

**예시**

**기본 예시**

```sql title=Query theme={null}
SELECT bitmaskToList(50) AS powers_list
```

```response title=Response theme={null}
┌─powers_list───┐
│ 2, 16, 32     │
└───────────────┘
```

<div id="char">
  ## char
</div>

도입 버전: v20.1.0

전달된 인수의 개수와 길이가 같고, 각 바이트가 해당 인수의 값을 갖는 문자열을 반환합니다. 숫자 타입의 여러 인수를 받을 수 있습니다.

인수 값이 `UInt8` 데이터 타입의 범위를 벗어나면, 반올림 및 오버플로우가 발생할 수 있는 방식으로 `UInt8`로 변환됩니다.

**구문**

```sql theme={null}
char(num1[, num2[, ...]])
```

**인수**

* `num1[, num2[, num3 ...]]` — 정수로 해석되는 숫자 인수입니다. [`(U)Int8/16/32/64`](/ko/reference/data-types/int-uint) 또는 [`Float*`](/ko/reference/data-types/float)

**반환 값**

주어진 바이트로 이루어진 문자열을 반환합니다. [`String`](/ko/reference/data-types/string)

**예시**

**기본 예시**

```sql title=Query theme={null}
SELECT char(104.1, 101, 108.9, 108.9, 111) AS hello;
```

```response title=Response theme={null}
┌─hello─┐
│ hello │
└───────┘
```

**임의의 인코딩 생성**

```sql title=Query theme={null}
-- 해당 바이트를 전달하여 임의 인코딩의 문자열을 구성할 수 있습니다.
-- 예: UTF8
SELECT char(0xD0, 0xBF, 0xD1, 0x80, 0xD0, 0xB8, 0xD0, 0xB2, 0xD0, 0xB5, 0xD1, 0x82) AS hello;
```

```response title=Response theme={null}
┌─hello──┐
│ привет │
└────────┘
```

<div id="hex">
  ## hex
</div>

도입 버전: v1.1.0

서로 다른 타입에 대해 아래 로직에 따라 인수의 16진수 표현을 포함한 문자열을 반환합니다:

| 유형                         | 설명                                                                                                                                                |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `(U)Int*`                  | 최상위 자릿수부터 최하위 자릿수까지 16진수 숫자("니블")를 출력합니다(빅 엔디안 또는 "사람이 읽기 쉬운" 순서). 가장 상위의 0이 아닌 바이트부터 시작하며(앞쪽의 0 바이트는 생략), 선행 숫자가 0이더라도 각 바이트의 두 자리는 항상 모두 출력합니다. |
| `Date` and `DateTime`      | 해당하는 정수 형식으로 포맷됩니다(`Date`는 epoch 이후 경과한 일 수, `DateTime`은 Unix timestamp 값).                                                                       |
| `String` and `FixedString` | 모든 바이트는 각각 두 자리 16진수로 그대로 인코딩됩니다. 0 바이트도 생략되지 않습니다.                                                                                               |
| `Float*` and `Decimal`     | 메모리에 표현된 형태로 인코딩됩니다. ClickHouse는 내부적으로 값을 항상 리틀 엔디안으로 표현하므로, 이에 맞춰 인코딩됩니다. 앞이나 뒤의 0 바이트도 생략되지 않습니다.                                               |
| `UUID`                     | 빅 엔디안 순서의 문자열로 인코딩됩니다.                                                                                                                            |

이 함수는 대문자 `A-F`를 사용하며, 접두사(`0x` 등)나 접미사(`h` 등)는 사용하지 않습니다.

**구문**

```sql theme={null}
hex(arg)
```

**인수**

* `arg` — 16진수로 변환할 값입니다. [`String`](/ko/reference/data-types/string) 또는 [`(U)Int*`](/ko/reference/data-types/int-uint) 또는 [`Float*`](/ko/reference/data-types/float) 또는 [`Decimal`](/ko/reference/data-types/decimal) 또는 [`Date`](/ko/reference/data-types/date) 또는 [`DateTime`](/ko/reference/data-types/datetime)

**반환 값**

인수의 16진수 표현을 담은 문자열을 반환합니다. [`String`](/ko/reference/data-types/string)

**예시**

**간단한 정수**

```sql title=Query theme={null}
SELECT hex(1)
```

```response title=Response theme={null}
01
```

**Float32 숫자**

```sql title=Query theme={null}
SELECT hex(toFloat32(number)) AS hex_presentation FROM numbers(15, 2)
```

```response title=Response theme={null}
┌─hex_presentation─┐
│ 00007041         │
│ 00008041         │
└──────────────────┘
```

**Float64 형 숫자**

```sql title=Query theme={null}
SELECT hex(toFloat64(number)) AS hex_presentation FROM numbers(15, 2)
```

```response title=Response theme={null}
┌─hex_presentation─┐
│ 0000000000002E40 │
│ 0000000000003040 │
└──────────────────┘
```

**UUID 변환**

```sql title=Query theme={null}
SELECT lower(hex(toUUID('61f0c404-5cb3-11e7-907b-a6006ad3dba0'))) AS uuid_hex
```

```response title=Response theme={null}
┌─uuid_hex─────────────────────────┐
│ 61f0c4045cb311e7907ba6006ad3dba0 │
└──────────────────────────────────┘
```

<div id="hilbertDecode">
  ## hilbertDecode
</div>

도입 버전: v24.6.0

Hilbert 곡선 인덱스를 다시 부호 없는 정수의 튜플로 디코딩하며, 이는 다차원 공간의 좌표를 나타냅니다.

`hilbertEncode` 함수와 마찬가지로, 이 함수는 두 가지 모드로 동작합니다:

* **간단**
* **확장**

**간단 모드**

최대 2개의 부호 없는 정수를 인수로 받아 `UInt64` 코드를 생성합니다.

**확장 모드**

첫 번째 인수로 범위 마스크(튜플)를 받고, 나머지 인수로 최대 2개의 부호 없는 정수를
받습니다. 마스크의 각 숫자는 해당 인수를 왼쪽으로 시프트할 비트 수를 설정하며,
그 결과 해당 범위 내에서 인수가 효과적으로 스케일링됩니다.

범위 확장은
범위(또는 카디널리티)가 크게 다른 인수들에 대해 비슷한 분포가 필요할 때 유용할 수 있습니다. 예를 들어 'IP Address' `(0...FFFFFFFF)`
및 'Country code' `(0...FF)`가 있습니다. 인코드 함수와 마찬가지로, 이는 최대 8개의
숫자로 제한됩니다.

**구문**

```sql theme={null}
hilbertDecode(tuple_size, code)
```

**인수**

* `tuple_size` — `2` 이하의 정수 값입니다. [`UInt8/16/32/64`](/ko/reference/data-types/int-uint) 또는 [`Tuple(UInt8/16/32/64)`](/ko/reference/data-types/tuple)
* `code` — `UInt64` 코드입니다. [`UInt64`](/ko/reference/data-types/int-uint)

**반환 값**

지정된 크기의 Tuple을 반환합니다. [`Tuple(UInt64)`](/ko/reference/data-types/tuple)

**예시**

**단순 모드**

```sql title=Query theme={null}
SELECT hilbertDecode(2, 31)
```

```response title=Response theme={null}
["3", "4"]
```

**단일 인수**

```sql title=Query theme={null}
-- 인수가 하나인 경우 Hilbert 코드는 항상 인수 자체입니다(튜플 형태).
SELECT hilbertDecode(1, 1)
```

```response title=Response theme={null}
["1"]
```

**확장 모드**

```sql title=Query theme={null}
-- 비트 시프트를 지정하는 튜플과 함께 단일 인수를 사용하면 그에 따라 오른쪽으로 시프트됩니다.
SELECT hilbertDecode(tuple(2), 32768)
```

```response title=Response theme={null}
["128"]
```

**컬럼 사용법**

```sql title=Query theme={null}
-- 먼저 테이블을 생성하고 데이터를 삽입합니다
CREATE TABLE hilbert_numbers(
    n1 UInt32,
    n2 UInt32
)
ENGINE=MergeTree()
ORDER BY n1 SETTINGS index_granularity_bytes = '10Mi';
insert into hilbert_numbers (*) values(1,2);

-- 함수 인수로 상수 대신 컬럼 이름을 사용합니다
SELECT untuple(hilbertDecode(2, hilbertEncode(n1, n2))) FROM hilbert_numbers;
```

```response title=Response theme={null}
1    2
```

<div id="hilbertEncode">
  ## hilbertEncode
</div>

지원 시작 버전: v24.6.0

부호 없는 정수 목록에 대한 힐버트 곡선 코드를 계산합니다.

이 함수는 두 가지 모드로 동작합니다.

* **단순**
* **확장**

**단순 모드**

최대 2개의 부호 없는 정수를 인수로 받아 UInt64 코드를 생성합니다.

**확장 모드**

첫 번째 인수로 범위 마스크([Tuple](/ko/reference/data-types/tuple))를 받고,
다른 인수로는 최대 2개의 [부호 없는 정수](/ko/reference/data-types/int-uint)를 받습니다.

마스크의 각 숫자는 해당 인수를 왼쪽으로 시프트할 비트 수를 지정하며,
결과적으로 해당 범위 내에서 인수를 스케일링합니다.

**구문**

```sql theme={null}
-- 단순 모드
hilbertEncode(args)

-- 확장 모드
hilbertEncode(range_mask, args)
```

**인수**

* `args` — 최대 2개의 `UInt` 값 또는 `UInt` 타입 컬럼. [`UInt8/16/32/64`](/ko/reference/data-types/int-uint)
* `range_mask` — 확장 모드에서는 최대 2개의 `UInt` 값 또는 `UInt` 타입 컬럼. [`UInt8/16/32/64`](/ko/reference/data-types/int-uint)

**반환 값**

`UInt64` 코드를 반환합니다. [`UInt64`](/ko/reference/data-types/int-uint)

**예시**

**기본 모드**

```sql title=Query theme={null}
SELECT hilbertEncode(3, 4)
```

```response title=Response theme={null}
31
```

**확장 모드**

```sql title=Query theme={null}
-- 범위 확장은 범위(또는 카디널리티)가 크게 다른 인수들에 대해 유사한 분포가 필요할 때 유용합니다.
-- 예: 'IP 주소' (0...FFFFFFFF)와 '국가 코드' (0...FF).
-- 참고: 튜플 크기는 나머지 인수의 개수와 같아야 합니다.
SELECT hilbertEncode((10, 6), 1024, 16)
```

```response title=Response theme={null}
4031541586602
```

**단일 인수**

```sql title=Query theme={null}
-- 튜플 없이 단일 인수만 제공된 경우, 차원 매핑이 필요하지 않으므로
-- 함수는 인수 자체를 Hilbert 인덱스로 반환합니다.
SELECT hilbertEncode(1)
```

```response title=Response theme={null}
1
```

**확장 모드의 단일 인수**

```sql title=Query theme={null}
-- 비트 시프트를 지정하는 tuple과 함께 단일 인수가 제공되면, 함수는
-- 해당 인수를 지정된 비트 수만큼 왼쪽으로 시프트합니다.
SELECT hilbertEncode(tuple(2), 128)
```

```response title=Response theme={null}
512
```

**컬럼 사용법**

```sql title=Query theme={null}
-- 먼저 테이블을 생성하고 데이터를 삽입합니다
CREATE TABLE hilbert_numbers(
    n1 UInt32,
    n2 UInt32
)
ENGINE=MergeTree()
ORDER BY n1;
insert into hilbert_numbers (*) values(1, 2);

-- 함수 인수로 상수 대신 컬럼 이름을 사용합니다
SELECT hilbertEncode(n1, n2) FROM hilbert_numbers;
```

```response title=Response theme={null}
13
```

<div id="mortonDecode">
  ## mortonDecode
</div>

도입 버전: v24.6.0

Morton 인코딩(ZCurve)을 해당하는 부호 없는 정수 튜플로 디코딩합니다.

`mortonEncode` 함수와 마찬가지로, 이 함수는 두 가지 모드로 동작합니다:

* **Simple**
* **Expanded**

**단순 모드**

첫 번째 인수로 결과 튜플의 크기를 받고, 두 번째 인수로 코드를 받습니다.

**확장 모드**

첫 번째 인수로 범위 마스크(튜플)를 받고, 두 번째 인수로 코드를 받습니다.
마스크의 각 숫자는 범위 축소 정도를 설정합니다:

* `1` - 축소 없음
* `2` - 2배 축소
* `3` - 3배 축소
  ⋮
* 최대 8배 축소

범위 확장은 범위(또는 카디널리티)가 크게 다른
인수들에 대해 비슷한 분포가 필요할 때 유용할 수 있습니다. 예: 'IP Address' `(0...FFFFFFFF)`
및 'Country code' `(0...FF)`. 인코딩 함수와 마찬가지로, 이는
최대 8개의 숫자로 제한됩니다.

**구문**

```sql theme={null}
-- 단순 모드
mortonDecode(tuple_size, code)

-- 확장 모드
mortonDecode(range_mask, code)
```

**인수**

* `tuple_size` — 8 이하의 정수 값입니다. [`UInt8/16/32/64`](/ko/reference/data-types/int-uint)
* `range_mask` — 확장 모드에서 각 인수에 적용되는 마스크입니다. 마스크는 부호 없는 정수로 이루어진 튜플입니다. 마스크의 각 숫자는 범위 축소량을 설정합니다. [`Tuple(UInt8/16/32/64)`](/ko/reference/data-types/tuple)
* `code` — UInt64 코드입니다. [`UInt64`](/ko/reference/data-types/int-uint)

**반환 값**

지정된 크기의 튜플을 반환합니다. [`Tuple(UInt64)`](/ko/reference/data-types/tuple)

**예시**

**단순 모드**

```sql title=Query theme={null}
SELECT mortonDecode(3, 53)
```

```response title=Response theme={null}
["1", "2", "3"]
```

**단일 인수**

```sql title=Query theme={null}
SELECT mortonDecode(1, 1)
```

```response title=Response theme={null}
["1"]
```

**확장 모드, 하나의 인수를 축소**

```sql title=Query theme={null}
SELECT mortonDecode(tuple(2), 32768)
```

```response title=Response theme={null}
["128"]
```

**컬럼 사용법**

```sql title=Query theme={null}
-- 먼저 테이블을 생성하고 데이터를 삽입합니다
CREATE TABLE morton_numbers(
    n1 UInt32,
    n2 UInt32,
    n3 UInt16,
    n4 UInt16,
    n5 UInt8,
    n6 UInt8,
    n7 UInt8,
    n8 UInt8
)
ENGINE=MergeTree()
ORDER BY n1;
INSERT INTO morton_numbers (*) values(1, 2, 3, 4, 5, 6, 7, 8);

-- 함수 인수로 상수 대신 컬럼 이름을 사용합니다
SELECT untuple(mortonDecode(8, mortonEncode(n1, n2, n3, n4, n5, n6, n7, n8))) FROM morton_numbers;
```

```response title=Response theme={null}
1 2 3 4 5 6 7 8
```

<div id="mortonEncode">
  ## mortonEncode
</div>

도입 버전: v24.6.0

부호 없는 정수 목록에 대한 Morton 인코딩(ZCurve)을 계산합니다.

이 함수는 두 가지 모드로 동작합니다.

* **Simple**
* *Expanded*\*

**Simple mode**

최대 8개의 부호 없는 정수를 인수로 받아 `UInt64` 코드를 생성합니다.

**Expanded mode**

첫 번째 인수로 범위 마스크([Tuple](/ko/reference/data-types/tuple))를 받고,
나머지 인수로 최대 8개의 [부호 없는 정수](/ko/reference/data-types/int-uint)를 받습니다.

마스크의 각 숫자는 범위 확장 정도를 설정합니다.

* 1 - 확장 없음
* 2 - 2배 확장
* 3 - 3배 확장
  ⋮
* 최대 8배 확장

**구문**

```sql theme={null}
-- 단순 모드
mortonEncode(args)

-- 확장 모드
mortonEncode(range_mask, args)
```

**인수**

* `args` — 앞서 언급한 타입의 부호 없는 정수 또는 해당 타입의 컬럼을 최대 8개까지 지정할 수 있습니다. [`UInt8/16/32/64`](/ko/reference/data-types/int-uint)
* `range_mask` — 확장 모드에서는 각 인수에 적용되는 마스크입니다. 마스크는 `1` - `8` 범위의 부호 없는 정수로 이루어진 튜플입니다. 마스크의 각 숫자는 범위 축소량을 설정합니다. [`Tuple(UInt8/16/32/64)`](/ko/reference/data-types/tuple)

**반환 값**

`UInt64` 코드를 반환합니다. [`UInt64`](/ko/reference/data-types/int-uint)

**예시**

**단순 모드**

```sql title=Query theme={null}
SELECT mortonEncode(1, 2, 3)
```

```response title=Response theme={null}
53
```

**확장 모드**

```sql title=Query theme={null}
-- 범위가 크게 다른 인수(또는 카디널리티가 다른 인수)에 대해 유사한 분포가 필요할 때
-- 범위 확장이 유용할 수 있습니다.
-- 예: 'IP Address' (0...FFFFFFFF)와 'Country code' (0...FF).
-- 참고: Tuple의 크기는 나머지 인수의 수와 같아야 합니다.
SELECT mortonEncode((1,2), 1024, 16)
```

```response title=Response theme={null}
1572864
```

**단일 인수**

```sql title=Query theme={null}
-- 인수가 하나인 경우 Morton 인코딩 결과는 항상 해당 인수 자체입니다
SELECT mortonEncode(1)
```

```response title=Response theme={null}
1
```

**확장 단일 인수**

```sql title=Query theme={null}
SELECT mortonEncode(tuple(2), 128)
```

```response title=Response theme={null}
32768
```

**컬럼 사용법**

```sql title=Query theme={null}
-- 먼저 테이블을 생성하고 데이터를 삽입합니다
CREATE TABLE morton_numbers(
    n1 UInt32,
    n2 UInt32,
    n3 UInt16,
    n4 UInt16,
    n5 UInt8,
    n6 UInt8,
    n7 UInt8,
    n8 UInt8
)
ENGINE=MergeTree()
ORDER BY n1;
INSERT INTO morton_numbers (*) values(1, 2, 3, 4, 5, 6, 7, 8);

-- 함수 인수로 상수 대신 컬럼 이름을 사용합니다
SELECT mortonEncode(n1, n2, n3, n4, n5, n6, n7, n8) FROM morton_numbers;
```

```response title=Response theme={null}
2155374165
```

<div id="sqidDecode">
  ## sqidDecode
</div>

도입 버전: v24.1.0

[sqid](https://sqids.org/)를 숫자 배열로 다시 변환합니다.

**구문**

```sql theme={null}
sqidDecode(sqid)
```

**인수**

* `sqid` — 디코딩할 sqid 값입니다. [`String`](/ko/reference/data-types/string)

**반환 값**

`sqid`를 디코딩한 숫자 배열을 반환합니다. [`Array(UInt64)`](/ko/reference/data-types/array)

**예시**

**사용 예시**

```sql title=Query theme={null}
SELECT sqidDecode('gXHfJ1C6dN');
```

```response title=Response theme={null}
┌─sqidDecode('gXHfJ1C6dN')─────┐
│ [1, 2, 3, 4, 5]              │
└──────────────────────────────┘
```

<div id="sqidEncode">
  ## sqidEncode
</div>

도입 버전: v24.1.0

숫자를 YouTube와 유사한 ID 문자열인 [sqid](https://sqids.org/)로 변환합니다.

**구문**

```sql theme={null}
sqidEncode(n1[, n2, ...])
```

**별칭**: `sqid`

**인수**

* `n1[, n2, ...]` — 개수에 제한이 없는 숫자입니다. [`UInt8/16/32/64`](/ko/reference/data-types/int-uint)

**반환 값**

해시 ID [`String`](/ko/reference/data-types/string)를 반환합니다.

**예시**

**사용 예시**

```sql title=Query theme={null}
SELECT sqidEncode(1, 2, 3, 4, 5);
```

```response title=Response theme={null}
┌─sqidEncode(1, 2, 3, 4, 5)─┐
│ gXHfJ1C6dN                │
└───────────────────────────┘
```

<div id="unbin">
  ## unbin
</div>

도입 버전: v21.8.0

인수에 있는 각 이진 숫자 쌍을 숫자로 해석한 뒤, 그 숫자가 나타내는 바이트로 변환합니다. 이 함수는 `bin`과 반대되는 연산을 수행합니다.

숫자형 인수에 대해 `unbin()`은 `bin()`의 역연산 결과를 반환하지 않습니다. 결과를 숫자로 변환하려면 `reverse` 및 `reinterpretAs<Type>` 함수를 사용할 수 있습니다.

<Note>
  `clickhouse-client`에서 `unbin`을 호출하면 바이너리 문자열이 UTF-8로 표시됩니다.
</Note>

이진 숫자 `0`과 `1`을 지원합니다. 이진 숫자의 개수는 8의 배수일 필요가 없습니다. 인수 문자열에 이진 숫자 이외의 문자가 포함되어 있으면
결과는 정의되지 않습니다(예외가 발생하지 않습니다).

**구문**

```sql theme={null}
unbin(arg)
```

**인수**

* `arg` — 이진 숫자를 임의 개수만큼 포함하는 문자열입니다. [`String`](/ko/reference/data-types/string)

**반환 값**

바이너리 문자열(BLOB)을 반환합니다. [`String`](/ko/reference/data-types/string)

**예시**

**기본 사용법**

```sql title=Query theme={null}
SELECT UNBIN('001100000011000100110010'), UNBIN('0100110101111001010100110101000101001100')
```

```response title=Response theme={null}
┌─unbin('001100000011000100110010')─┬─unbin('0100110101111001010100110101000101001100')─┐
│ 012                               │ MySQL                                             │
└───────────────────────────────────┴───────────────────────────────────────────────────┘
```

**Number로 변환**

```sql title=Query theme={null}
SELECT reinterpretAsUInt64(reverse(unbin('1110'))) AS num
```

```response title=Response theme={null}
┌─num─┐
│  14 │
└─────┘
```

<div id="unhex">
  ## unhex
</div>

도입 버전: v1.1.0

[`hex`](#hex)의 반대 연산을 수행합니다. (인수의) 각 16진수 숫자 쌍을 숫자로 해석한 다음, 해당 숫자가 나타내는 바이트로 변환합니다. 반환 값은 바이너리 문자열(BLOB)입니다.

결과를 숫자로 변환하려면 `reverse` 및 `reinterpretAs<Type>` 함수를 사용할 수 있습니다.

<Note>
  `clickhouse-client`는 문자열을 UTF-8로 해석합니다.
  이로 인해 `hex`가 반환한 값이 예상과 다르게 표시될 수 있습니다.
</Note>

대문자와 소문자 `A-F`를 모두 지원합니다.
16진수 숫자의 개수는 짝수일 필요가 없습니다.
홀수인 경우 마지막 숫자는 `00-0F` 바이트의 하위 4비트로 해석됩니다.
인수 문자열에 16진수 숫자가 아닌 문자가 포함되어 있으면 구현에 따라 정의된 결과가 반환됩니다(예외는 발생하지 않습니다).
숫자 인수에는 unhex()가 hex(N)의 역연산을 수행하지 않습니다.

**구문**

```sql theme={null}
unhex(arg)
```

**인수**

* `arg` — 임의 개수의 16진수 숫자를 포함하는 문자열입니다. [`String`](/ko/reference/data-types/string) 또는 [`FixedString`](/ko/reference/data-types/fixedstring)

**반환 값**

바이너리 문자열(BLOB)을 반환합니다. [`String`](/ko/reference/data-types/string)

**예시**

**기본 사용법**

```sql title=Query theme={null}
SELECT unhex('303132'), UNHEX('4D7953514C')
```

```response title=Response theme={null}
┌─unhex('303132')─┬─unhex('4D7953514C')─┐
│ 012             │ MySQL               │
└─────────────────┴─────────────────────┘
```

**숫자로 변환**

```sql title=Query theme={null}
SELECT reinterpretAsUInt64(reverse(unhex('FFF'))) AS num
```

```response title=Response theme={null}
┌──num─┐
│ 4095 │
└──────┘
```
