Try it Live
Run Base64 examples in the interactive playground
Utilities
Utility functions for calculating base64 encoding and decoding sizes.Size Calculation Functions
- TypeScript
Base64.calcEncodedSize(dataLength)
Calculates size of base64-encoded output given input data length. Useful for pre-allocating buffers before encoding.Formula: Math.ceil(dataLength / 3) * 4dataLength: number- Length of data to encode in bytes
number - Size of base64 output in charactersExample:- Every 3 bytes encode to 4 base64 characters
- Partial groups padded to 4 characters
- Result always multiple of 4
Base64.calcDecodedSize(encodedLength)
- TypeScript
Calculates maximum size of decoded output given base64 string length. Useful for pre-allocating buffers before decoding.Formula: Parameters:Defined in: primitives/Base64/BrandedBase64/calcDecodedSize.js:7Algorithm:
Math.floor((encodedLength * 3) / 4) - paddingencodedLength: number- Length of base64 string in characters
number - Maximum size of decoded output in bytesExample:- Every 4 base64 characters decode to 3 bytes
- Returns maximum size (actual may be smaller due to padding)
- For exact size, must decode and check
Usage Patterns
Pre-allocating Buffers
Memory Estimation
Batch Processing with Size Limits
Validation with Size Checks
Size Optimization
Stream Processing
Size Calculation Reference
Encoding Size Examples
| Input Bytes | Output Characters | Ratio |
|---|---|---|
| 0 | 0 | - |
| 1 | 4 | 4.00 |
| 2 | 4 | 2.00 |
| 3 | 4 | 1.33 |
| 6 | 8 | 1.33 |
| 10 | 16 | 1.60 |
| 20 | 28 | 1.40 |
| 100 | 136 | 1.36 |
| 1024 | 1368 | 1.34 |
Decoding Size Examples
| Input Characters | Max Output Bytes | Ratio |
|---|---|---|
| 0 | 0 | - |
| 4 | 3 | 0.75 |
| 8 | 6 | 0.75 |
| 12 | 9 | 0.75 |
| 16 | 12 | 0.75 |
| 28 | 21 | 0.75 |
| 136 | 102 | 0.75 |
| 1368 | 1026 | 0.75 |
Mathematical Properties
Encoding Formula
Decoding Formula
Size Relationships
Performance
Size calculations are pure mathematical operations with O(1) complexity:Related
- Encoding - Encoding to base64 format
- Decoding - Decoding base64 strings
- Validation - Validating base64 format
- BrandedBase64 - Tree-shakeable API

