英文:
How to print a number as hexadecimal in Zig?
问题
pub fn main() void {
const foo: u8 = 128;
std.debug.print("{}\n", .{foo}); // "128"
}
The above prints 128
as expected.
How can the value be printed as hexadecimal instead?
英文:
const std = @import("std");
pub fn main() void {
const foo: u8 = 128;
std.debug.print("{}\n", .{foo}); // "128"
}
The above prints 128
as expected.
How can the value be printed as hexadecimal instead?
答案1
得分: 1
将`x`或`X`放入大括号中。还有其他选项:
```zig
const std = @import("std");
pub fn main() void {
// 在 Zig v0.10.1 中测试过
const foo: u8 = 26;
std.debug.print("0x{x}\n", .{foo}); // "0x1a"
std.debug.print("0x{X}\n", .{foo}); // "0x1A"
const bar: u16 = 1;
std.debug.print("0x{x}\n", .{bar}); // "0x1"
std.debug.print("0x{x:2}\n", .{bar}); // "0x 1"
std.debug.print("0x{x:4}\n", .{bar}); // "0x 1"
std.debug.print("0x{x:0>4}\n", .{bar}); // "0x0001"
const baz: u16 = 43;
std.debug.print("0x{x:0>4}\n", .{baz}); // "0x002b"
std.debug.print("0x{X:0>8}\n", .{baz}); // "0x0000002B"
const qux: u32 = 0x1a2b3c;
std.debug.print("0x{X:0>2}\n", .{qux}); // "0x1A2B3C"(不截断)
std.debug.print("0x{x:0>8}\n", .{qux}); // "0x001a2b3c"
}
有关占位符的更多信息,请参阅 https://github.com/ziglang/zig/blob/master/lib/std/fmt.zig
<details>
<summary>英文:</summary>
Put `x` or `X` inside the curly brackets.
There are additional options as well:
```zig
const std = @import("std");
pub fn main() void {
// Tested with Zig v0.10.1
const foo: u8 = 26;
std.debug.print("0x{x}\n", .{foo}); // "0x1a"
std.debug.print("0x{X}\n", .{foo}); // "0x1A"
const bar: u16 = 1;
std.debug.print("0x{x}\n", .{bar}); // "0x1"
std.debug.print("0x{x:2}\n", .{bar}); // "0x 1"
std.debug.print("0x{x:4}\n", .{bar}); // "0x 1"
std.debug.print("0x{x:0>4}\n", .{bar}); // "0x0001"
const baz: u16 = 43;
std.debug.print("0x{x:0>4}\n", .{baz}); // "0x002b"
std.debug.print("0x{X:0>8}\n", .{baz}); // "0x0000002B"
const qux: u32 = 0x1a2b3c;
std.debug.print("0x{X:0>2}\n", .{qux}); // "0x1A2B3C" (not cut off)
std.debug.print("0x{x:0>8}\n", .{qux}); // "0x001a2b3c"
}
You can read more about the placeholders at https://github.com/ziglang/zig/blob/master/lib/std/fmt.zig
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论