[PATCH v3 04/16] Add FormatUInt64{, Hex}() for formatting numbers in a signal safe manner

Peter Hutterer peter.hutterer at who-t.net
Thu May 10 23:23:18 PDT 2012


On Mon, Apr 16, 2012 at 11:14:21AM -0700, Chase Douglas wrote:
> Signed-off-by: Chase Douglas <chase.douglas at canonical.com>

Reviewed-by: Peter Hutterer <peter.hutterer at who-t.net> but _please_ write
tests for these.

Cheers,
  Peter

> ---
>  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