Categories
Tags
algorithms APIT Arc arm assembly asynchronous base64 BitHacks Blogging box c clang-format client cmake compiler concat concurrency const_fn contravariant cos covariant cpp Customization cybersecurity DataStructure db debugging Demo deserialization discrete doc DP dtruss Dynamic Example FFI flat_map format FP fsanitize Functional functions futures Fuwari GATs gccrs generics gitignore glibc GUI hacking hashmap haskell heap interop invariant iterator join justfile kernel LaTeX leak LFU linux lto MachineLearning macOS Markdown math ML mmap nc OnceLock optimization OS panic parallels perf physics pin postgresql radare2 release reverse RPIT rust sanitizer science Science serialization server shift sin SmallProjects socket std strace String StringView strip strlen surrealdb SWAR swisstable synchronous tan toml traits triangulation UnsafeRust utf16 utf8 Video wsl 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/