Skip to content

allow bytes to be printed-out as hex (#1358) #1451

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 1, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions std/fmt/index.zig
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,11 @@ pub fn formatText(
comptime var width = 0;
if (fmt.len > 1) width = comptime (parseUnsigned(usize, fmt[1..], 10) catch unreachable);
return formatBuf(bytes, width, context, Errors, output);
} else if ((fmt[0] == 'x') or (fmt[0] == 'X') ) {
for (bytes) |c| {
try formatInt(c, 16, fmt[0] == 'X', 0, context, Errors, output);
}
return;
} else @compileError("Unknown format character: " ++ []u8{fmt[0]});
}
return output(context, bytes);
Expand Down Expand Up @@ -1271,6 +1276,12 @@ test "fmt.format" {

try testFmt("E.Two", "{}", inst);
}
//print bytes as hex
{
const some_bytes = "\xCA\xFE\xBA\xBE";
try testFmt("lowercase: cafebabe\n", "lowercase: {x}\n", some_bytes);
try testFmt("uppercase: CAFEBABE\n", "uppercase: {X}\n", some_bytes);
}
}

fn testFmt(expected: []const u8, comptime template: []const u8, args: ...) !void {
Expand Down