> ## Documentation Index
> Fetch the complete documentation index at: https://voltaire.tevm.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Base64 Encoding

> Encoding bytes and strings to base64 format

<Card title="Try it Live" icon="play" href="https://playground.tevm.sh?example=primitives/base64.ts">
  Run Base64 examples in the interactive playground
</Card>

# Encoding

Methods for encoding binary data and strings to base64 format.

## Standard Base64 Encoding

<Tabs>
  <Tab title="TypeScript">
    ### `Base64.encode(data)`

    Encodes bytes to standard base64 string using RFC 4648 alphabet (A-Z, a-z, 0-9, +, /) with padding.

    ```typescript theme={null}
    const data = new Uint8Array([72, 101, 108, 108, 111])
    const encoded = Base64.encode(data)
    // "SGVsbG8="

    // Works with any binary data
    const binary = new Uint8Array([0xff, 0xfe, 0xfd])
    const encoded2 = Base64.encode(binary)
    // "/v79"
    ```

    **Parameters:**

    * `data: Uint8Array` - Binary data to encode

    **Returns:** `Base64String` - Standard base64-encoded string with padding

    **Example:**

    ```typescript theme={null}
    // Encode transaction hash
    const hash = Bytes32() // 32-byte hash
    const b64Hash = Base64.encode(hash)
    console.log(b64Hash.length) // 44 characters (32 * 4/3 rounded up)
    ```

    Defined in: [primitives/Base64/BrandedBase64/encode.js:17](https://github.com/evmts/voltaire/blob/main/src/primitives/Base64/BrandedBase64/encode.js)
  </Tab>
</Tabs>

### `Base64.encodeString(str)`

Encodes UTF-8 string to standard base64. Internally converts string to bytes using `TextEncoder`, then encodes to base64.

```typescript theme={null}
const message = "Hello, world!"
const encoded = Base64.encodeString(message)
// "SGVsbG8sIHdvcmxkIQ=="

// Works with Unicode
const unicode = "Hello, 世界!"
const encodedUnicode = Base64.encodeString(unicode)

// Decode back to original
const decoded = Base64.decodeToString(encodedUnicode)
console.log(decoded === unicode) // true
```

**Parameters:**

* `str: string` - UTF-8 string to encode

**Returns:** `Base64String` - Base64-encoded string

**Example:**

```typescript theme={null}
// Encode JSON data
const json = JSON.stringify({ foo: "bar", num: 42 })
const encoded = Base64.encodeString(json)

// Later decode and parse
const decoded = Base64.decodeToString(encoded)
const obj = JSON.parse(decoded)
```

Defined in: [primitives/Base64/BrandedBase64/encodeString.js:14](https://github.com/evmts/voltaire/blob/main/src/primitives/Base64/BrandedBase64/encodeString.js)

## URL-Safe Base64 Encoding

<Tabs>
  <Tab title="TypeScript">
    ### `Base64.encodeUrlSafe(data)`

    Encodes bytes to URL-safe base64 string. Uses URL-safe alphabet (A-Z, a-z, 0-9, -, \_) and removes padding characters.

    **Differences from standard base64:**

    * Replaces `+` with `-`
    * Replaces `/` with `_`
    * Removes `=` padding

    ```typescript theme={null}
    const data = new Uint8Array([255, 254, 253])
    const encoded = Base64.encodeUrlSafe(data)
    // URL-safe, no padding

    // Safe for URLs
    const url = `https://example.com/data/${encoded}`

    // Safe for filenames
    const filename = `cache-${encoded}.dat`
    ```

    **Parameters:**

    * `data: Uint8Array` - Binary data to encode

    **Returns:** `Base64UrlString` - URL-safe base64 string without padding

    **Example:**

    ```typescript theme={null}
    // Encode token for URL
    const tokenBytes = Bytes16() // 16-byte random token
    crypto.getRandomValues(tokenBytes)
    const token = Base64.encodeUrlSafe(tokenBytes)

    // Use in URL without encoding
    const apiUrl = `https://api.example.com/auth?token=${token}`
    ```

    Defined in: [primitives/Base64/BrandedBase64/encodeUrlSafe.js:19](https://github.com/evmts/voltaire/blob/main/src/primitives/Base64/BrandedBase64/encodeUrlSafe.js)
  </Tab>
</Tabs>

### `Base64.encodeStringUrlSafe(str)`

Encodes UTF-8 string to URL-safe base64. Combines `TextEncoder` with URL-safe base64 encoding.

```typescript theme={null}
const email = "user@example.com"
const encoded = Base64.encodeStringUrlSafe(email)
// No +, /, or = characters - safe for URLs

// Use in URL path or query parameter
const url = `/users/${encoded}`
```

**Parameters:**

* `str: string` - UTF-8 string to encode

**Returns:** `Base64UrlString` - URL-safe base64 string

**Example:**

```typescript theme={null}
// Encode state parameter for OAuth
const state = JSON.stringify({
  returnUrl: "/dashboard",
  timestamp: Date.now()
})
const encodedState = Base64.encodeStringUrlSafe(state)
const oauthUrl = `https://oauth.example.com/authorize?state=${encodedState}`
```

Defined in: [primitives/Base64/BrandedBase64/encodeStringUrlSafe.js:9](https://github.com/evmts/voltaire/blob/main/src/primitives/Base64/BrandedBase64/encodeStringUrlSafe.js)

## Usage Patterns

### Encoding with Size Calculation

```typescript theme={null}
// Pre-calculate encoded size
const dataSize = 1024
const encodedSize = Base64.calcEncodedSize(dataSize)

// Allocate exact buffer size needed
const data = new Uint8Array(dataSize)
const encoded = Base64.encode(data)
console.log(encoded.length === encodedSize) // true
```

### Choosing Standard vs URL-Safe

```typescript theme={null}
// Use standard for general data encoding
const serialized = Base64.encodeString(JSON.stringify(data))

// Use URL-safe when output appears in URLs
const urlSafeId = Base64.encodeUrlSafe(idBytes)
const link = `https://example.com/item/${urlSafeId}` // No escaping needed

// Use URL-safe for filenames
const filename = `cache-${Base64.encodeUrlSafe(hash)}.bin`
```

### Encoding Large Data

```typescript theme={null}
// For large data, consider chunking
function encodeChunked(data: Uint8Array, chunkSize = 1024): string[] {
  const chunks: string[] = []
  for (let i = 0; i < data.length; i += chunkSize) {
    const chunk = data.slice(i, i + chunkSize)
    chunks.push(Base64.encode(chunk))
  }
  return chunks
}

// Decode back
function decodeChunked(chunks: string[]): Uint8Array {
  const decoded = chunks.map(Base64.decode)
  const totalLength = decoded.reduce((sum, arr) => sum + arr.length, 0)
  const result = new Uint8Array(totalLength)
  let offset = 0
  for (const chunk of decoded) {
    result.set(chunk, offset)
    offset += chunk.length
  }
  return result
}
```

### Binary Data Encoding

```typescript theme={null}
// Encode Ethereum address (20 bytes)
const address = new Uint8Array(20)
const b64Address = Base64.encode(address)

// Encode transaction signature (65 bytes)
const signature = new Uint8Array(65)
const b64Sig = Base64.encode(signature)

// Encode arbitrary binary
const binaryData = new Uint8Array([0x00, 0xff, 0x80, 0x7f])
const encoded = Base64.encode(binaryData)
```

## Encoding Algorithm

Standard base64 encoding process:

1. **Group input:** Split input bytes into 3-byte groups
2. **Convert to base64:** Each 3-byte group becomes 4 base64 characters
3. **Padding:** If final group has fewer than 3 bytes, pad with `=`

### Visual: 3 Bytes → 4 Characters

```
Input bytes:     [01001000] [01100101] [01101100]
                  H (72)     e (101)    l (108)

6-bit groups:    [010010] [000110] [010101] [101100]
                   18       6        21       44

Base64 chars:     S         G        V        s
                 (A-Z: 0-25, a-z: 26-51, 0-9: 52-61, +/: 62-63)
```

### Complete Example: "Hello" → "SGVsbG8="

```
Input:    H      e      l      l      o
Hex:      48     65     6c     6c     6f
Binary:   01001000 01100101 01101100 01101100 01101111
                  ↓ 6-bit groups
6-bits:   010010 | 000110 | 010101 | 101100 | 011011 | 000110 | 1111xx
Index:    18     | 6      | 21     | 44     | 27     | 6      | 60
Base64:   S      | G      | V      | s      | b      | G      | 8      | = (padding)
Output:   S G V s b G 8 =
```

**Padding Rules:**

* Input length % 3 == 0: No padding (`SGVs`)
* Input length % 3 == 1: Add `==` (`SGVsbG8=`)
* Input length % 3 == 2: Add `=` (`SGVsbGk=`)

URL-safe encoding applies character substitutions after standard encoding:

```typescript theme={null}
// Standard: SGVs+G8/bG8=
// URL-safe: SGVs-G8_bG8  (no padding)
// Changes: + → -, / → _, = removed
```

## Related

* [Decoding](/primitives/base64/decoding) - Decoding base64 strings
* [Validation](/primitives/base64/validation) - Validating base64 format
* [Utilities](/primitives/base64/utilities) - Size calculations
* [BrandedBase64](/primitives/base64/branded-base64) - Tree-shakeable API
