From 260d29b1ecb631ba71b1940771edc4ae065be83c Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Fri, 31 Oct 2025 18:13:23 +0200 Subject: [PATCH] builtin: add .hex() methods to the `rune` and `char` types too (#25635) --- vlib/builtin/hex_test.v | 30 ++++++++++++++++++++++++++++++ vlib/builtin/int.v | 16 ++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 vlib/builtin/hex_test.v diff --git a/vlib/builtin/hex_test.v b/vlib/builtin/hex_test.v new file mode 100644 index 000000000..0b5088d1d --- /dev/null +++ b/vlib/builtin/hex_test.v @@ -0,0 +1,30 @@ +fn test_hex_methods_on_u8() { + assert u8(1).hex() == '01' + assert u8(` `).hex() == '20' + assert u8(255).hex() == 'ff' +} + +fn test_hex_methods_on_byte() { + assert byte(1).hex() == '01' + assert byte(` `).hex() == '20' + assert byte(255).hex() == 'ff' +} + +fn test_hex_methods_on_char() { + assert char(1).hex() == '01' + assert char(` `).hex() == '20' + assert char(255).hex() == 'ff' +} + +fn test_hex_method_on_runes() { + assert ` `.hex() == '20' + assert `喂`.hex() == '5582' + // latin: + assert `A`.hex() == '41' + assert `Z`.hex() == '5a' + // cyrillic: + assert `Д`.hex() == '414' + assert `Я`.hex() == '42f' + // emojies: + assert `💣`.hex() == '1f4a3' +} diff --git a/vlib/builtin/int.v b/vlib/builtin/int.v index 76a7f98ae..40ec74a85 100644 --- a/vlib/builtin/int.v +++ b/vlib/builtin/int.v @@ -340,6 +340,22 @@ pub fn (nn u8) hex() string { return u64_to_hex(nn, 2) } +// hex returns a hexadecimal representation of `c` (as an 8 bit unsigned number). +// The output is zero padded for values below 16. +// Example: assert char(`A`).hex() == '41' +// Example: assert char(`Z`).hex() == '5a' +// Example: assert char(` `).hex() == '20' +pub fn (c char) hex() string { + return u8(c).hex() +} + +// hex returns a hexadecimal representation of the rune `r` (as a 32 bit unsigned number). +// Example: assert `A`.hex() == '41' +// Example: assert `💣`.hex() == '1f4a3' +pub fn (r rune) hex() string { + return u32(r).hex() +} + // hex returns the value of the `i8` as a hexadecimal `string`. // Note that the output is zero padded for values below 16. // Example: assert i8(8).hex() == '08' -- 2.39.5