Add a simple macro calculating the size needed to store the string
representation of an integer type (both signed and unsigned) together
with the terminating NUL-character.

Suggested-by: Michael Conrad <mcon...@intellitree.com>
Signed-off-by: Bartosz Golaszewski <bartekg...@gmail.com>
---
 include/libbb.h | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/include/libbb.h b/include/libbb.h
index 64e8490..826804a 100644
--- a/include/libbb.h
+++ b/include/libbb.h
@@ -298,6 +298,23 @@ struct BUG_off_t_size_is_misdetected {
 
 #define BIT(nr) (1UL << (nr))
 
+/*
+ * Calculate the buffer size needed to hold the string representation of the
+ * given integer type.
+ *
+ * We're using 2.4 sizeof-to-buffer-size ratio and add one byte to round the
+ * result up, one byte for the terminating NUL-character and another one for
+ * the potential '-' character for signed types. This results in the following
+ * buffer lengths for common integer types.
+ *
+ * sizeof(type)     calculated bufsize     actual bufsize needed
+ *            1                      5                         5
+ *            2                      7                         7
+ *            4                     12                        12
+ *            8                     22                        21
+ */
+#define INT_BUF_MAX(type) (sizeof(type) * 24 / 10 + 3)
+
 /* Macros for min/max.  */
 #ifndef MIN
 #define MIN(a,b) (((a)<(b))?(a):(b))
-- 
2.1.4

_______________________________________________
busybox mailing list
busybox@busybox.net
http://lists.busybox.net/mailman/listinfo/busybox

Reply via email to