Categories
Tags
algorithms APIT arm assembly asynchronous base64 Blogging box c clang-format cmake compiler concurrency const_fn contravariant cos covariant cpp Customization cybersecurity DataStructure db Demo deserialization discrete doc DP Dynamic Example FFI flat_map FP Functional functions futures Fuwari GATs gccrs generics gitignore GUI hacking hashmap haskell heap interop invariant iterator justfile kernel LaTeX LFU linux MachineLearning Markdown math ML OnceLock optimization OS parallels perf physics pin postgresql release RPIT rust science Science serialization shift sin SmallProjects std String surrealdb swisstable synchronous tan traits triangulation utf16 utf8 Video x86_64 xilem zig
116 words
1 minutes
240301_zig_base64
link
1. Base64 Math Formula
Base64 encodes 3 bytes → 4 characters.
Mathematical Relationship
Bit Transformation
- 3 bytes (24 bits):
[aaaaaaaabbbbbbbbcccccccc]- Split into 6-bit groups:
[aaaaaa][aabbbb][bbbbcc][cccccc]- Each 6-bit value maps to one Base64 alphabet character.
zig code(ver 0.16)
const std = @import("std");
fn base64_encode(allocator: std.mem.Allocator, input: []const u8) ![]const u8 {
const alphabet_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"[0..64].*;
var encoder = std.base64.Base64Encoder.init(alphabet_chars, '=');
const size = encoder.calcSize(input.len);
const buf = try allocator.alloc(u8, size);
const result = encoder.encode(buf, input);
return result;
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
const result = try base64_encode(allocator, "h");
std.debug.print("h __result : {s}\n", .{result});
const result02 = try base64_encode(allocator, "hello");
std.debug.print("hello ___result02 : {s}\n", .{result02});
}240301_zig_base64
https://younghakim7.github.io/blog/posts/240301_zig_base64/