홈으로 돌아가기

Base64 인코딩 원리 분석: 왜 3바이트 이진 데이터가 4바이트 텍스트로 변할까?

웹 개발을 진행하다 보면 이미지 파일을 HTML 안에 내장하거나, 바이너리 파일을 JSON 구조 안에 텍스트 데이터 형태로 집어넣기 위해 **Base64 인코딩**을 사용하곤 합니다. 인코딩을 마친 파일은 원본보다 크기가 대략 33% 정도 커지게 되는데, 여기에는 수학적이고 기하학적인 비트 분할 설계 원리가 담겨 있습니다. 이번 글에서는 Base64 인코딩의 세부 동작 과정과 작동 수학식을 자세히 분석합니다.

1. Base64 인코딩의 정의와 목적

컴퓨터는 모든 데이터를 0과 1로 된 이진(Binary) 포맷으로 처리합니다. 하지만 이메일 전송(MIME)이나 HTTP 텍스트 전송 환경에서는 제어 문자나 라인 피드(LF/CR) 같은 시스템별 해석 차이 때문에 바이너리가 깨질 위험이 있습니다. Base64는 시스템간 공통적으로 깨지지 않고 해독할 수 있는 **64개의 안전한 ASCII 인쇄 가능 문자** (영어 대문자 A-Z, 소문자 a-z, 숫자 0-9, 특수기호 +, /) 조합으로 데이터를 100% 무해하게 포맷팅하는 데 목적이 있습니다.

2. 24비트의 매핑 연산 원리 (3Byte -> 4Byte)

핵심 원리는 최소공배수를 활용한 비트 분할에 있습니다. 컴퓨터의 1바이트(Byte)는 8비트(Bit)입니다. 반면 Base64는 64개($2^6$)의 부호만을 사용하므로 하나의 부호 문자가 **6비트(Bit)**를 나타낼 수 있습니다. 따라서 8비트 3개(총 24비트)를 모아서 6비트 4개(총 24비트)로 잘라서 문자로 치환하는 연산을 수행합니다.

비트 분할 레이아웃 상세

  • 원본 데이터: [Byte 1 (8bits)] [Byte 2 (8bits)] [Byte 3 (8bits)] = 총 24비트
  • 인코딩 분할: [6bits] [6bits] [6bits] [6bits] = 총 24비트
  • 결과 문자: [Char 1] [Char 2] [Char 3] [Char 4] = 총 4글자의 텍스트

이 분할식으로 인해, 3바이트 단위의 원본 바이너리가 인코딩 과정을 거치면 4바이트(4글자)의 텍스트가 되므로 데이터량이 수학적으로 정확히 33.3% 증가하는 용량 오버헤드가 발생하게 됩니다.

3. 패딩(Padding) 규칙과 등호(=) 기호의 의미

그렇다면 인코딩하려는 원본 데이터의 크기가 딱 3바이트 배수로 나누어떨어지지 않을 때는 어떻게 될까요? 이때 사용하는 보정 문자가 바로 **패딩(Padding)**용 등호 = 기호입니다.

  • 1바이트(8비트)가 남을 때: 뒤에 0을 4비트 패딩하여 12비트로 만들고, 이를 6비트씩 두 개의 Base64 문자로 변환한 뒤 남는 뒤쪽 두 칸에 패딩 기호 ==를 붙여 자리를 채웁니다.
  • 2바이트(16비트)가 남을 때: 뒤에 0을 2비트 패딩하여 18비트로 만들고, 이를 6비트씩 세 개의 Base64 문자로 변환한 뒤 남는 마지막 한 칸에 패딩 기호 =를 붙여 채웁니다.

4. 클라이언트 사이드 변환 가이드

**anyTools**의 Base64 변환기는 데이터 전송 보안을 위해 외부 서버를 일절 거치지 않고, 브라우저 로컬 엔진에서 자바스크립트의 표준 바이너리 버퍼 객체들을 이용해 인/디코딩 처리를 수행합니다. 브라우저 내장 API인 btoa()atob()는 UTF-8 다국어 문자 처리에 한계가 있으므로, anyTools는 아래와 같이 안전한 TypedArray 변환 공식을 채택하고 있습니다.

// 다국어 안전 인코딩
function encodeBase64(str) {
    const bytes = new TextEncoder().encode(str);
    let binString = "";
    for (let i = 0; i < bytes.byteLength; i++) {
        binString += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binString);
}

5. 요약

Base64 인코딩은 텍스트 전용 환경에서 바이너리 데이터를 안전하게 묶어 전달하는 핵심 인코더 도구입니다. anyTools는 6비트 비트 시프팅(Shift) 매핑 알고리즘을 모바일에 맞추어 고속화하여 제공하며, 이미지나 대용량 텍스트 변환 시에도 클라이언트 메모리 최적화를 보장합니다.

When developing web applications, you often use **Base64 Encoding** to embed images in HTML or include binary data inside JSON formats. Since Base64 converts 3 bytes of binary data into 4 characters of text, it increases file size by about 33%. In this article, we analyze the mathematical and bit-level mechanics of the Base64 encoding pipeline.

1. Definition and Goal of Base64

Computers treat all data in binary (0 and 1) format. However, standard network transmission tools like Email or HTTP texts sometimes interpret certain byte blocks as control codes, causing files to break. Base64 translates binary files into **64 safe, printable ASCII characters** (A-Z, a-z, 0-9, +, and /) to prevent parsing errors.

2. The 24-Bit Mapping Process (3Bytes to 4Bytes)

The core logic lies in the least common multiple of 8-bit bytes and 6-bit Base64 character indexes. Base64 gathers 3 bytes (24 bits) of raw data and divides them into 4 blocks of 6 bits each ($2^6 = 64$):

Bit Partitioning Layout

  • Original Binary: [Byte 1 (8bits)] [Byte 2 (8bits)] [Byte 3 (8bits)] = 24 bits
  • Base64 Partition: [6bits] [6bits] [6bits] [6bits] = 24 bits
  • Resulting ASCII Text: [Char 1] [Char 2] [Char 3] [Char 4] = 4 characters

Because every 3 bytes of raw data become 4 bytes of text, the encoded output naturally carries a **33.3% size overhead** compared to the original payload.

3. Padding Rules and the Equal Sign (=)

When the original binary size is not a multiple of 3 bytes, **Padding** with equal signs (=) is applied:

  • 1 Remaining Byte (8 bits): Padded with 4 zeros to make 12 bits, translated into 2 Base64 characters, and finished with double padding (==).
  • 2 Remaining Bytes (16 bits): Padded with 2 zeros to make 18 bits, translated into 3 Base64 characters, and finished with single padding (=).

4. Client-Side Implementation

**anyTools** processes all encoding in the user's browser, preventing private data leakage. While native btoa() and atob() fail with multibyte UTF-8 characters, anyTools relies on stable TypedArray conversion logic:

// Safe UTF-8 Base64 Encoding
function encodeBase64(str) {
    const bytes = new TextEncoder().encode(str);
    let binString = "";
    for (let i = 0; i < bytes.byteLength; i++) {
        binString += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binString);
}

5. Summary

Base64 is a key standard for safely carrying binary payloads over plain text interfaces. anyTools simplifies this using fast bitwise shifting scripts optimized for mobile devices, enabling smooth client-side operations.