changeset 479:77ad030e82c9

Add th_get_int() helper function.
author Matti Hamalainen <ccr@tnsp.org>
date Tue, 27 Nov 2018 07:48:58 +0200
parents b1e80180818a
children 2aa2052cb17d
files th_string.c th_string.h
diffstat 2 files changed, 76 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/th_string.c	Mon Jul 09 09:25:51 2018 +0300
+++ b/th_string.c	Tue Nov 27 07:48:58 2018 +0200
@@ -1014,6 +1014,81 @@
 }
 
 
+BOOL th_get_int(const char *str, unsigned int *value, BOOL *neg)
+{
+    int ch;
+    BOOL hex = FALSE;
+
+    // Is the value negative?
+    if (*str == '-')
+    {
+        if (neg == NULL)
+            return FALSE;
+
+        *neg = TRUE;
+        str++;
+    }
+    else
+    if (neg != NULL)
+        *neg = FALSE;
+
+    // Is it hexadecimal?
+    if (*str == '$')
+    {
+        hex = TRUE;
+        str++;
+    }
+    else
+    if (str[0] == '0' && str[1] == 'x')
+    {
+        hex = TRUE;
+        str += 2;
+    }
+
+    // Parse the value
+    *value = 0;
+    if (hex)
+    {
+        while ((ch = *str++))
+        {
+            if (ch >= '0' && ch <= '9')
+            {
+                *value <<= 4;
+                *value |= ch - '0';
+            }
+            else
+            if (ch >= 'A' && ch <= 'F')
+            {
+                *value <<= 4;
+                *value |= ch - 'A' + 10;
+            }
+            else
+            if (ch >= 'a' && ch <= 'f')
+            {
+                *value <<= 4;
+                *value |= ch - 'a' + 10;
+            }
+            else
+                return FALSE;
+        }
+    }
+    else
+    {
+        while ((ch = *str++))
+        {
+            if (ch >= '0' && ch <= '9')
+            {
+                *value *= 10;
+                *value += ch - '0';
+            }
+            else
+                return FALSE;
+        }
+    }
+    return TRUE;
+}
+
+
 static void th_pad(FILE *outFile, int count)
 {
     while (count--)
--- a/th_string.h	Mon Jul 09 09:25:51 2018 +0300
+++ b/th_string.h	Tue Nov 27 07:48:58 2018 +0200
@@ -157,6 +157,7 @@
 
 int     th_get_hex_triplet(const char *str);
 BOOL    th_get_boolean(const char *str, BOOL *value);
+BOOL    th_get_int(const char *str, unsigned int *value, BOOL *neg);
 
 void    th_print_wrap(FILE *fh, const char *str, int spad, int rpad, int width);