116 words
1 minutes
240301_zig_base64

link#

1. Base64 Math Formula#

  • Base64 encodes 3 bytes → 4 characters.

  • Mathematical Relationship

output_length=4n3\text{output\_length} = 4 \cdot \left\lceil \frac{n}{3} \right\rceil

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/
Author
YoungHa
Published at
2024-03-01