Skip to content

Instantly share code, notes, and snippets.

@Shoghy
Last active March 11, 2025 14:09
Show Gist options
  • Select an option

  • Save Shoghy/e4a78503ebe6d1d6c366e5db9f3b0155 to your computer and use it in GitHub Desktop.

Select an option

Save Shoghy/e4a78503ebe6d1d6c366e5db9f3b0155 to your computer and use it in GitHub Desktop.
Base64 encoder
const std = @import("std");
const gpa = std.heap.page_allocator;
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub fn main() !void {
const text = "AAA";
var base64Length = (text.len / 3) * 4;
if ((text.len % 3) > 0) {
base64Length += 4;
}
var base64 = try gpa.alloc(u8, base64Length);
defer gpa.free(base64);
var textIndex: usize = 0;
var base64Index: usize = 0;
while (textIndex < text.len) {
var b: u8 = text[textIndex] >> 2;
base64[base64Index] = chars[b];
base64Index += 1;
b = text[textIndex] & 0b11;
b <<= 4;
textIndex += 1;
if (textIndex >= text.len) {
base64[base64Index] = chars[b];
base64[base64Index + 1] = '=';
base64[base64Index + 2] = '=';
break;
}
b += text[textIndex] >> 4;
base64[base64Index] = chars[b];
base64Index += 1;
b = text[textIndex] & 0b1111;
b <<= 2;
textIndex += 1;
if (textIndex >= text.len) {
base64[base64Index] = chars[b];
base64[base64Index + 1] = '=';
break;
}
b += text[textIndex] >> 6;
base64[base64Index] = chars[b];
base64Index += 1;
b = text[textIndex] & 0b111111;
base64[base64Index] = chars[b];
base64Index += 1;
textIndex += 1;
}
std.debug.print("{s}\n", .{base64});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment