[llvm] [ADT][bugfix] Fixed extra leading zero in uhextostr (PR #141097)

Bushev Dmitry via llvm-commits llvm-commits at lists.llvm.org
Thu May 22 09:20:36 PDT 2025


https://github.com/dybv-sc created https://github.com/llvm/llvm-project/pull/141097

fixed bug: if fixed-width mode uhextostr() is used with value zero, it prints extra '0' character.

>From aa33f1b88b3dda7a62db03e36914edad291bd334 Mon Sep 17 00:00:00 2001
From: Dmitry Bushev <dmitry.bushev at syntacore.com>
Date: Thu, 22 May 2025 16:31:07 +0300
Subject: [PATCH] [ADT][bugfix] Fixed extra leading zero in uhextostr

fixed bug: if fixed-width mode uhextostr() is used with value zero, it prints
extra '0' character.
---
 llvm/include/llvm/ADT/StringExtras.h    | 3 ++-
 llvm/unittests/ADT/StringExtrasTest.cpp | 1 +
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/llvm/include/llvm/ADT/StringExtras.h b/llvm/include/llvm/ADT/StringExtras.h
index a2cc36dd8caad..7d81c63485be2 100644
--- a/llvm/include/llvm/ADT/StringExtras.h
+++ b/llvm/include/llvm/ADT/StringExtras.h
@@ -179,7 +179,8 @@ inline std::string utohexstr(uint64_t X, bool LowerCase = false,
   char Buffer[17];
   char *BufPtr = std::end(Buffer);
 
-  if (X == 0) *--BufPtr = '0';
+  if (X == 0 && !Width)
+    *--BufPtr = '0';
 
   for (unsigned i = 0; Width ? (i < Width) : X; ++i) {
     unsigned char Mod = static_cast<unsigned char>(X) & 15;
diff --git a/llvm/unittests/ADT/StringExtrasTest.cpp b/llvm/unittests/ADT/StringExtrasTest.cpp
index 36908a98aa2ae..fbaed38da5943 100644
--- a/llvm/unittests/ADT/StringExtrasTest.cpp
+++ b/llvm/unittests/ADT/StringExtrasTest.cpp
@@ -144,6 +144,7 @@ TEST(StringExtrasTest, ToAndFromHex) {
 }
 
 TEST(StringExtrasTest, UINT64ToHex) {
+  EXPECT_EQ(utohexstr(0x0u, false, 2), "00");
   EXPECT_EQ(utohexstr(0xA0u), "A0");
   EXPECT_EQ(utohexstr(0xA0u, false, 4), "00A0");
   EXPECT_EQ(utohexstr(0xA0u, false, 8), "000000A0");



More information about the llvm-commits mailing list