[PATCH v2 06/14] Add FormatUInt64() for formatting numbers in a signal safe manner

Chase Douglas chase.douglas at canonical.com
Mon Apr 9 11:17:32 PDT 2012


Signed-off-by: Chase Douglas <chase.douglas at canonical.com>
---
 include/misc.h |    2 ++
 os/utils.c     |   40 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 42 insertions(+), 0 deletions(-)

diff --git a/include/misc.h b/include/misc.h
index 41c1333..3f7d07e 100644
--- a/include/misc.h
+++ b/include/misc.h
@@ -229,6 +229,8 @@ pad_to_int32(const int bytes)
 }
 
 extern char **xstrtokenize(const char *str, const char *separators);
+extern void FormatUInt64(uint64_t num, char *string);
+extern void FormatUInt64Hex(uint64_t num, char *string);
 
 /**
  * Compare the two version numbers comprising of major.minor.
diff --git a/os/utils.c b/os/utils.c
index 9954114..12252d7 100644
--- a/os/utils.c
+++ b/os/utils.c
@@ -1784,3 +1784,43 @@ xstrtokenize(const char *str, const char *separators)
     free(list);
     return NULL;
 }
+
+/* Format a number into a string in a signal safe manner. The string should be
+ * at least 20 characters in order to handle all uint64_t values. */
+void
+FormatUInt64(uint64_t num, char *string)
+{
+    uint64_t divisor;
+    int len;
+    int i;
+
+    for (len = 1, divisor = 10; num / divisor; len++, divisor *= 10);
+
+    for (i = len, divisor = 1; i > 0; i--, divisor *= 10)
+        string[i - 1] = '0' + ((num / divisor) % 10);
+
+    string[len] = '\0';
+}
+
+/* Format a number into a hexadecimal string in a signal safe manner. The string
+ * should be at least 17 characters in order to handle all uint64_t values. */
+void
+FormatUInt64Hex(uint64_t num, char *string)
+{
+    uint64_t divisor;
+    int len;
+    int i;
+
+    for (len = 1, divisor = 0x10; num / divisor; len++, divisor *= 0x10);
+
+    for (i = len, divisor = 1; i > 0; i--, divisor *= 0x10) {
+        int val = (num / divisor) % 0x10;
+
+        if (val < 10)
+            string[i - 1] = '0' + val;
+        else
+            string[i - 1] = 'a' + val - 10;
+    }
+
+    string[len] = '\0';
+}
-- 
1.7.9.1



More information about the xorg-devel mailing list