Skip to contentSkip to conversation

tools/nolibc: Optimise and common up the number to ascii functions

PATCH In review [email protected] 2 participants 5 messages Feb 8 – Feb 17 Nolibc header file

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 tools/nolibc: Optimise and common up the number to ascii functions

From: David Laight <[email protected]>

Implement u[64]to[ah]_r() using a common function that uses multiply by reciprocal to generate the least significant digit first and then reverses the string.

On 32bit this is six multiplies (with 64bit product) for each output digit. I think the old utoa_r() always did 36 multiplies and a lot of subtracts - so this is likely faster even for 32bit values. Definitely better for 64bit values (especially small ones).

Clearly shifts are faster for base 16, but reversing the output buffer makes a big difference.

Sharing the code reduces the footprint (unless gcc decides to constant fold the functions).
Definitely helps vfprintf() where the constants get loaded and a single call is done.
Also makes it cheap to add octal support to vfprintf for completeness.

---

Willy T. acked v1, but I've changed the code slightly since.

Changes for v2:
- Update some comments.
- Add _nolibc_/_NOLIBC_ prefix to the visible symbols.
- Change _NOLIBC_U64TOA_RECIP() to return a slightly larger value and include the 'low by low' multiply in 32bit systems so that the correction for a slightly small quotient isn't needed.
The code is now slightly smaller on x86-64.

 tools/include/nolibc/stdlib.h | 150 ++++++++++++++--------------------
 1 file changed, 62 insertions(+), 88 deletions(-)
tools/include/nolibc/stdlib.h +62 -88
index f184e108ed0a..62d2fdc8c8d0 100644
@@ -188,36 +188,70 @@ void *realloc(void *old_ptr, size_t new_size)
 	return ret;
 }
 
-/* Converts the unsigned long integer <in> to its hex representation into
+/* Converts the unsigned 64bit integer <in> to base <base> ascii into
  * buffer <buffer>, which must be long enough to store the number and the
- * trailing zero (17 bytes for "ffffffffffffffff" or 9 for "ffffffff"). The
- * buffer is filled from the first byte, and the number of characters emitted
- * (not counting the trailing zero) is returned. The function is constructed
- * in a way to optimize the code size and avoid any divide that could add a
- * dependency on large external functions.
+ * trailing zero. The buffer is filled from the first byte, and the number
+ * of characters emitted (not counting the trailing zero) is returned.
+ * The function uses 'multiply by reciprocal' for the divisions and
+ * requires the caller pass the correct reciprocal.
+ *
+ * Note that unlike __div64_const32() in asm-generic/div64.h the divisor
+ * is never large enough to need a bias added.
+ * The division is correct for all divisors up to at least 1G.
+ *
+ * __int128 isn't used for mips because gcc prior to 10.0 will call
+ * __multi3 for MIPS64r6.
  */
-static __attribute__((unused))
-int utoh_r(unsigned long in, char *buffer)
+#define _NOLIBC_U64TOA_RECIP(base) ((~0ULL / (base)) + 1)
+static __attribute__((unused, noinline))
+int _nolibc_u64toa_base(uint64_t in, char *buffer, unsigned int base, uint64_t recip)
 {
-	signed char pos = (~0UL > 0xfffffffful) ? 60 : 28;
-	int digits = 0;
-	int dig;
+	unsigned int digits = 0;
+	unsigned int dig;
+	uint64_t q;
+	char *p;
 
+	/* Generate least significant digit first */
 	do {
-		dig = in >> pos;
-		in -= (uint64_t)dig << pos;
-		pos -= 4;
-		if (dig || digits || pos < 0) {
-			if (dig > 9)
-				dig += 'a' - '0' - 10;
-			buffer[digits++] = '0' + dig;
-		}
-	} while (pos >= 0);
+#if defined(__SIZEOF_INT128__) && !defined(__mips__)
+		q = ((unsigned __int128)in * recip) >> 64;
+#else
+		uint64_t p = ((uint64_t)(uint32_t)in * (uint32_t)recip) >> 32;
+		p += (uint32_t)in * (recip >> 32);
+		q = (in >> 32) * (recip >> 32) + (p >> 32);
+		p = (uint32_t)p + (in >> 32) * (uint32_t)recip;
+		q += p >> 32;
+#endif
+		dig = in - q * base;
+		if (dig > 9)
+			dig += 'a' - '0' - 10;
+		buffer[digits++] = '0' + dig;
+	} while ((in = q));
 
 	buffer[digits] = 0;
+
+	/* Order reverse to result */
+	for (p = buffer + digits - 1; p > buffer; buffer++, p--) {
+		dig = *buffer;
+		*buffer = *p;
+		*p = dig;
+	}
+
 	return digits;
 }
 
+/* Converts the unsigned long integer <in> to its hex representation into
+ * buffer <buffer>, which must be long enough to store the number and the
+ * trailing zero (17 bytes for "ffffffffffffffff" or 9 for "ffffffff"). The
+ * buffer is filled from the first byte, and the number of characters emitted
+ * (not counting the trailing zero) is returned.
+ */
+static __inline__ __attribute__((unused))
+int utoh_r(unsigned long in, char *buffer)
+{
+	return _nolibc_u64toa_base(in, buffer, 16, _NOLIBC_U64TOA_RECIP(16));
+}
+
 /* converts unsigned long <in> to an hex string using the static itoa_buffer
  * and returns the pointer to that string.
  */
@@ -233,30 +267,11 @@ char *utoh(unsigned long in)
  * trailing zero (21 bytes for 18446744073709551615 in 64-bit, 11 for
  * 4294967295 in 32-bit). The buffer is filled from the first byte, and the
  * number of characters emitted (not counting the trailing zero) is returned.
- * The function is constructed in a way to optimize the code size and avoid
- * any divide that could add a dependency on large external functions.
  */
-static __attribute__((unused))
+static __inline__ __attribute__((unused))
 int utoa_r(unsigned long in, char *buffer)
 {
-	unsigned long lim;
-	int digits = 0;
-	int pos = (~0UL > 0xfffffffful) ? 19 : 9;
-	int dig;
-
-	do {
-		for (dig = 0, lim = 1; dig < pos; dig++)
-			lim *= 10;
-
-		if (digits || in >= lim || !pos) {
-			for (dig = 0; in >= lim; dig++)
-				in -= lim;
-			buffer[digits++] = '0' + dig;
-		}
-	} while (pos--);
-
-	buffer[digits] = 0;
-	return digits;
+	return _nolibc_u64toa_base(in, buffer, 10, _NOLIBC_U64TOA_RECIP(10));
 }
 
 /* Converts the signed long integer <in> to its string representation into
@@ -324,34 +339,12 @@ char *utoa(unsigned long in)
  * buffer <buffer>, which must be long enough to store the number and the
  * trailing zero (17 bytes for "ffffffffffffffff"). The buffer is filled from
  * the first byte, and the number of characters emitted (not counting the
- * trailing zero) is returned. The function is constructed in a way to optimize
- * the code size and avoid any divide that could add a dependency on large
- * external functions.
+ * trailing zero) is returned.
  */
-static __attribute__((unused))
+static __inline__ __attribute__((unused))
 int u64toh_r(uint64_t in, char *buffer)
 {
-	signed char pos = 60;
-	int digits = 0;
-	int dig;
-
-	do {
-		if (sizeof(long) >= 8) {
-			dig = (in >> pos) & 0xF;
-		} else {
-			/* 32-bit platforms: avoid a 64-bit shift */
-			uint32_t d = (pos >= 32) ? (in >> 32) : in;
-			dig = (d >> (pos & 31)) & 0xF;
-		}
-		if (dig > 9)
-			dig += 'a' - '0' - 10;
-		pos -= 4;
-		if (dig || digits || pos < 0)
-			buffer[digits++] = '0' + dig;
-	} while (pos >= 0);
-
-	buffer[digits] = 0;
-	return digits;
+	return _nolibc_u64toa_base(in, buffer, 16, _NOLIBC_U64TOA_RECIP(16));
 }
 
 /* converts uint64_t <in> to an hex string using the static itoa_buffer and
@@ -368,31 +361,12 @@ char *u64toh(uint64_t in)
  * buffer <buffer>, which must be long enough to store the number and the
  * trailing zero (21 bytes for 18446744073709551615). The buffer is filled from
  * the first byte, and the number of characters emitted (not counting the
- * trailing zero) is returned. The function is constructed in a way to optimize
- * the code size and avoid any divide that could add a dependency on large
- * external functions.
+ * trailing zero) is returned.
  */
-static __attribute__((unused))
+static __inline__ __attribute__((unused))
 int u64toa_r(uint64_t in, char *buffer)
 {
-	unsigned long long lim;
-	int digits = 0;
-	int pos = 19; /* start with the highest possible digit */
-	int dig;
-
-	do {
-		for (dig = 0, lim = 1; dig < pos; dig++)
-			lim *= 10;
-
-		if (digits || in >= lim || !pos) {
-			for (dig = 0; in >= lim; dig++)
-				in -= lim;
-			buffer[digits++] = '0' + dig;
-		}
-	} while (pos--);
-
-	buffer[digits] = 0;
-	return digits;
+	return _nolibc_u64toa_base(in, buffer, 10, _NOLIBC_U64TOA_RECIP(10));
 }
 
 /* Converts the signed 64-bit integer <in> to its string representation into
Signature · 1 line
2.39.5
#1 lore raw
Quoted 5 lines · On Sun, 8 Feb 2026 19:53:08 +0000 [email protected] wrote:

From: David Laight <[email protected]>

Implement u[64]to[ah]_r() using a common function that uses multiply by reciprocal to generate the least significant digit first and then reverses the string.

Self-nak on this version :-(

The division code can end up generating a negative remainder for very large values (probably only ones over 1<<63).
The code would need to be slightly more complicated and require an extra parameter.
So I'll revert to the v1 version which contains the correction for underestimates of the quotient and high remainders.

I'll send a v3 after the merge window.

David

Quoted 232 lines

On 32bit this is six multiplies (with 64bit product) for each output digit. I think the old utoa_r() always did 36 multiplies and a lot of subtracts - so this is likely faster even for 32bit values. Definitely better for 64bit values (especially small ones).

Clearly shifts are faster for base 16, but reversing the output buffer makes a big difference.

Sharing the code reduces the footprint (unless gcc decides to constant fold the functions).
Definitely helps vfprintf() where the constants get loaded and a single call is done.
Also makes it cheap to add octal support to vfprintf for completeness.

---

Willy T. acked v1, but I've changed the code slightly since.

Changes for v2:
- Update some comments.
- Add _nolibc_/_NOLIBC_ prefix to the visible symbols.
- Change _NOLIBC_U64TOA_RECIP() to return a slightly larger value and include the 'low by low' multiply in 32bit systems so that the correction for a slightly small quotient isn't needed.
The code is now slightly smaller on x86-64.

 tools/include/nolibc/stdlib.h | 150 ++++++++++++++--------------------
 1 file changed, 62 insertions(+), 88 deletions(-)
tools/include/nolibc/stdlib.h +62 -88
index f184e108ed0a..62d2fdc8c8d0 100644
@@ -188,36 +188,70 @@ void *realloc(void *old_ptr, size_t new_size)
 	return ret;
 }
 
-/* Converts the unsigned long integer <in> to its hex representation into
+/* Converts the unsigned 64bit integer <in> to base <base> ascii into
  * buffer <buffer>, which must be long enough to store the number and the
- * trailing zero (17 bytes for "ffffffffffffffff" or 9 for "ffffffff"). The
- * buffer is filled from the first byte, and the number of characters emitted
- * (not counting the trailing zero) is returned. The function is constructed
- * in a way to optimize the code size and avoid any divide that could add a
- * dependency on large external functions.
+ * trailing zero. The buffer is filled from the first byte, and the number
+ * of characters emitted (not counting the trailing zero) is returned.
+ * The function uses 'multiply by reciprocal' for the divisions and
+ * requires the caller pass the correct reciprocal.
+ *
+ * Note that unlike __div64_const32() in asm-generic/div64.h the divisor
+ * is never large enough to need a bias added.
+ * The division is correct for all divisors up to at least 1G.
+ *
+ * __int128 isn't used for mips because gcc prior to 10.0 will call
+ * __multi3 for MIPS64r6.
  */
-static __attribute__((unused))
-int utoh_r(unsigned long in, char *buffer)
+#define _NOLIBC_U64TOA_RECIP(base) ((~0ULL / (base)) + 1)
+static __attribute__((unused, noinline))
+int _nolibc_u64toa_base(uint64_t in, char *buffer, unsigned int base, uint64_t recip)
 {
-	signed char pos = (~0UL > 0xfffffffful) ? 60 : 28;
-	int digits = 0;
-	int dig;
+	unsigned int digits = 0;
+	unsigned int dig;
+	uint64_t q;
+	char *p;
 
+	/* Generate least significant digit first */
 	do {
-		dig = in >> pos;
-		in -= (uint64_t)dig << pos;
-		pos -= 4;
-		if (dig || digits || pos < 0) {
-			if (dig > 9)
-				dig += 'a' - '0' - 10;
-			buffer[digits++] = '0' + dig;
-		}
-	} while (pos >= 0);
+#if defined(__SIZEOF_INT128__) && !defined(__mips__)
+		q = ((unsigned __int128)in * recip) >> 64;
+#else
+		uint64_t p = ((uint64_t)(uint32_t)in * (uint32_t)recip) >> 32;
+		p += (uint32_t)in * (recip >> 32);
+		q = (in >> 32) * (recip >> 32) + (p >> 32);
+		p = (uint32_t)p + (in >> 32) * (uint32_t)recip;
+		q += p >> 32;
+#endif
+		dig = in - q * base;
+		if (dig > 9)
+			dig += 'a' - '0' - 10;
+		buffer[digits++] = '0' + dig;
+	} while ((in = q));
 
 	buffer[digits] = 0;
+
+	/* Order reverse to result */
+	for (p = buffer + digits - 1; p > buffer; buffer++, p--) {
+		dig = *buffer;
+		*buffer = *p;
+		*p = dig;
+	}
+
 	return digits;
 }
 
+/* Converts the unsigned long integer <in> to its hex representation into
+ * buffer <buffer>, which must be long enough to store the number and the
+ * trailing zero (17 bytes for "ffffffffffffffff" or 9 for "ffffffff"). The
+ * buffer is filled from the first byte, and the number of characters emitted
+ * (not counting the trailing zero) is returned.
+ */
+static __inline__ __attribute__((unused))
+int utoh_r(unsigned long in, char *buffer)
+{
+	return _nolibc_u64toa_base(in, buffer, 16, _NOLIBC_U64TOA_RECIP(16));
+}
+
 /* converts unsigned long <in> to an hex string using the static itoa_buffer
  * and returns the pointer to that string.
  */
@@ -233,30 +267,11 @@ char *utoh(unsigned long in)
  * trailing zero (21 bytes for 18446744073709551615 in 64-bit, 11 for
  * 4294967295 in 32-bit). The buffer is filled from the first byte, and the
  * number of characters emitted (not counting the trailing zero) is returned.
- * The function is constructed in a way to optimize the code size and avoid
- * any divide that could add a dependency on large external functions.
  */
-static __attribute__((unused))
+static __inline__ __attribute__((unused))
 int utoa_r(unsigned long in, char *buffer)
 {
-	unsigned long lim;
-	int digits = 0;
-	int pos = (~0UL > 0xfffffffful) ? 19 : 9;
-	int dig;
-
-	do {
-		for (dig = 0, lim = 1; dig < pos; dig++)
-			lim *= 10;
-
-		if (digits || in >= lim || !pos) {
-			for (dig = 0; in >= lim; dig++)
-				in -= lim;
-			buffer[digits++] = '0' + dig;
-		}
-	} while (pos--);
-
-	buffer[digits] = 0;
-	return digits;
+	return _nolibc_u64toa_base(in, buffer, 10, _NOLIBC_U64TOA_RECIP(10));
 }
 
 /* Converts the signed long integer <in> to its string representation into
@@ -324,34 +339,12 @@ char *utoa(unsigned long in)
  * buffer <buffer>, which must be long enough to store the number and the
  * trailing zero (17 bytes for "ffffffffffffffff"). The buffer is filled from
  * the first byte, and the number of characters emitted (not counting the
- * trailing zero) is returned. The function is constructed in a way to optimize
- * the code size and avoid any divide that could add a dependency on large
- * external functions.
+ * trailing zero) is returned.
  */
-static __attribute__((unused))
+static __inline__ __attribute__((unused))
 int u64toh_r(uint64_t in, char *buffer)
 {
-	signed char pos = 60;
-	int digits = 0;
-	int dig;
-
-	do {
-		if (sizeof(long) >= 8) {
-			dig = (in >> pos) & 0xF;
-		} else {
-			/* 32-bit platforms: avoid a 64-bit shift */
-			uint32_t d = (pos >= 32) ? (in >> 32) : in;
-			dig = (d >> (pos & 31)) & 0xF;
-		}
-		if (dig > 9)
-			dig += 'a' - '0' - 10;
-		pos -= 4;
-		if (dig || digits || pos < 0)
-			buffer[digits++] = '0' + dig;
-	} while (pos >= 0);
-
-	buffer[digits] = 0;
-	return digits;
+	return _nolibc_u64toa_base(in, buffer, 16, _NOLIBC_U64TOA_RECIP(16));
 }
 
 /* converts uint64_t <in> to an hex string using the static itoa_buffer and
@@ -368,31 +361,12 @@ char *u64toh(uint64_t in)
  * buffer <buffer>, which must be long enough to store the number and the
  * trailing zero (21 bytes for 18446744073709551615). The buffer is filled from
  * the first byte, and the number of characters emitted (not counting the
- * trailing zero) is returned. The function is constructed in a way to optimize
- * the code size and avoid any divide that could add a dependency on large
- * external functions.
+ * trailing zero) is returned.
  */
-static __attribute__((unused))
+static __inline__ __attribute__((unused))
 int u64toa_r(uint64_t in, char *buffer)
 {
-	unsigned long long lim;
-	int digits = 0;
-	int pos = 19; /* start with the highest possible digit */
-	int dig;
-
-	do {
-		for (dig = 0, lim = 1; dig < pos; dig++)
-			lim *= 10;
-
-		if (digits || in >= lim || !pos) {
-			for (dig = 0; in >= lim; dig++)
-				in -= lim;
-			buffer[digits++] = '0' + dig;
-		}
-	} while (pos--);
-
-	buffer[digits] = 0;
-	return digits;
+	return _nolibc_u64toa_base(in, buffer, 10, _NOLIBC_U64TOA_RECIP(10));
 }
 
 /* Converts the signed 64-bit integer <in> to its string representation into
#2 lore raw
Quoted 5 lines · David Laight
Quoted 2 lines · On Sun, 8 Feb 2026 19:53:08 +0000 [email protected] wrote:

From: David Laight <[email protected]>

Quoted 8 lines
Quoted 3 lines

Implement u[64]to[ah]_r() using a common function that uses multiply by reciprocal to generate the least significant digit first and then reverses the string.

Self-nak on this version :-(

The division code can end up generating a negative remainder for very large values (probably only ones over 1<<63).

Ok. Maybe some tests for these edgecases are in order, too. Do you want to add them?

Thomas

#3 lore raw
Quoted 10 lines · On Mon, 16 Feb 2026 19:46:12 +0100 Thomas Weißschuh <[email protected]>…
Quoted 9 lines · David Laight
Quoted 5 lines · On Sun, 8 Feb 2026 19:53:08 +0000 [email protected] wrote:

From: David Laight <[email protected]>

Implement u[64]to[ah]_r() using a common function that uses multiply by reciprocal to generate the least significant digit first and then reverses the string.

Quoted 7 lines
Quoted 4 lines

Self-nak on this version :-(

The division code can end up generating a negative remainder for very large values (probably only ones over 1<<63).

Ok. Maybe some tests for these edgecases are in order, too. Do you want to add them?

The problem is I'm not sure how to decide where they are.
The v1 patch is fine, it expects to get a large remainder and then fixes up the error.
I could make the code just work for 8, 10 and 16 - but that is 'wimping out'.

David

Quoted 3 lines

Thomas

#4 lore raw
Quoted 18 lines · On Mon, 16 Feb 2026 22:16:20 +0000 David Laight <[email protected]>…
Quoted 15 lines · On Mon, 16 Feb 2026 19:46:12 +0100 Thomas Weißschuh <[email protected]>…
Quoted 13 lines · David Laight
Quoted 5 lines · On Sun, 8 Feb 2026 19:53:08 +0000 [email protected] wrote:

From: David Laight <[email protected]>

Implement u[64]to[ah]_r() using a common function that uses multiply by reciprocal to generate the least significant digit first and then reverses the string.

Self-nak on this version :-(

The division code can end up generating a negative remainder for very large values (probably only ones over 1<<63).

Quoted 6 lines
Quoted 2 lines

Ok. Maybe some tests for these edgecases are in order, too. Do you want to add them?

The problem is I'm not sure how to decide where they are. The v1 patch is fine, it expects to get a large remainder and then fixes up the error.

I think I can convince myself that the error on the quotient is less than 2 (and some of that 2 is the remainder that becomes the digit). Which means the maximum remainder (for base 10) is less than 20. So a simple:

	if (digit >= base) {
		digit -= base;
		quotient++;
	}

suffices (without s/if/while/).

David