📝

【Zig】バイト列と16進数の相互変換

2024/04/15に公開

まずは文字リテラル、エスケープシーケンス、配列表記の復習

const print = @import("std").debug.print;

pub fn main() !void {
    const str = "あ";
    const str2 = "\u{3042}";
    const str3 = "\xe3\x81\x82";
    const str4 = [_]u8 { '\xe3', '\x81', '\x82' };
    const str5 = [_]u8 { 0xe3, 0x81, 0x82 };
    const str6: [3]u8 = .{ 0xe3, 0x81, 0x82 };

    print("{s}\n" ** 6, .{ str, str2, str3, str4, str5, str6 });
}

変換に取り組む。std.fmtbytesToHexbytesToHex を使う

const std = @import("std");
const print = std.debug.print;
const bytesToHex = std.fmt.bytesToHex;
const hexToBytes = std.fmt.hexToBytes;

pub fn main() !void {
    const str = "あいう";
    var buf: [str.len]u8 = undefined;

    const encoded = bytesToHex(str, .lower);
    const decoded = try hexToBytes(&buf, &encoded);

    print("{s}\n" ** 2, .{ encoded, decoded });
}

Zig 0.12 開発版では std.debug.dump_hex が導入された

const dump_hex = @import("std").debug.dump_hex;

pub fn main() !void {
    dump_hex("あいう");
}

実行結果は次のとおり

00000000010d9b17  E3 81 82 E3 81 84 E3 81  86                       .........

Discussion