在Zig中如何将数字以十六进制打印出来?

huangapple go评论111阅读模式
英文:

How to print a number as hexadecimal in Zig?

问题

  1. pub fn main() void {
  2. const foo: u8 = 128;
  3. std.debug.print("{}\n", .{foo}); // "128"
  4. }

The above prints 128 as expected.
How can the value be printed as hexadecimal instead?

英文:
  1. const std = @import("std");
  2. pub fn main() void {
  3. const foo: u8 = 128;
  4. std.debug.print("{}\n", .{foo}); // "128"
  5. }

The above prints 128 as expected.
How can the value be printed as hexadecimal instead?

答案1

得分: 1

  1. `x``X`放入大括号中。还有其他选项:
  2. ```zig
  3. const std = @import("std");
  4. pub fn main() void {
  5. // 在 Zig v0.10.1 中测试过
  6. const foo: u8 = 26;
  7. std.debug.print("0x{x}\n", .{foo}); // "0x1a"
  8. std.debug.print("0x{X}\n", .{foo}); // "0x1A"
  9. const bar: u16 = 1;
  10. std.debug.print("0x{x}\n", .{bar}); // "0x1"
  11. std.debug.print("0x{x:2}\n", .{bar}); // "0x 1"
  12. std.debug.print("0x{x:4}\n", .{bar}); // "0x 1"
  13. std.debug.print("0x{x:0>4}\n", .{bar}); // "0x0001"
  14. const baz: u16 = 43;
  15. std.debug.print("0x{x:0>4}\n", .{baz}); // "0x002b"
  16. std.debug.print("0x{X:0>8}\n", .{baz}); // "0x0000002B"
  17. const qux: u32 = 0x1a2b3c;
  18. std.debug.print("0x{X:0>2}\n", .{qux}); // "0x1A2B3C"(不截断)
  19. std.debug.print("0x{x:0>8}\n", .{qux}); // "0x001a2b3c"
  20. }

有关占位符的更多信息,请参阅 https://github.com/ziglang/zig/blob/master/lib/std/fmt.zig

  1. <details>
  2. <summary>英文:</summary>
  3. Put `x` or `X` inside the curly brackets.
  4. There are additional options as well:
  5. ```zig
  6. const std = @import(&quot;std&quot;);
  7. pub fn main() void {
  8. // Tested with Zig v0.10.1
  9. const foo: u8 = 26;
  10. std.debug.print(&quot;0x{x}\n&quot;, .{foo}); // &quot;0x1a&quot;
  11. std.debug.print(&quot;0x{X}\n&quot;, .{foo}); // &quot;0x1A&quot;
  12. const bar: u16 = 1;
  13. std.debug.print(&quot;0x{x}\n&quot;, .{bar}); // &quot;0x1&quot;
  14. std.debug.print(&quot;0x{x:2}\n&quot;, .{bar}); // &quot;0x 1&quot;
  15. std.debug.print(&quot;0x{x:4}\n&quot;, .{bar}); // &quot;0x 1&quot;
  16. std.debug.print(&quot;0x{x:0&gt;4}\n&quot;, .{bar}); // &quot;0x0001&quot;
  17. const baz: u16 = 43;
  18. std.debug.print(&quot;0x{x:0&gt;4}\n&quot;, .{baz}); // &quot;0x002b&quot;
  19. std.debug.print(&quot;0x{X:0&gt;8}\n&quot;, .{baz}); // &quot;0x0000002B&quot;
  20. const qux: u32 = 0x1a2b3c;
  21. std.debug.print(&quot;0x{X:0&gt;2}\n&quot;, .{qux}); // &quot;0x1A2B3C&quot; (not cut off)
  22. std.debug.print(&quot;0x{x:0&gt;8}\n&quot;, .{qux}); // &quot;0x001a2b3c&quot;
  23. }

You can read more about the placeholders at https://github.com/ziglang/zig/blob/master/lib/std/fmt.zig

huangapple
  • 本文由 发表于 2023年6月6日 08:43:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定