www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/07/28/14:13:00

Message-Id: <199807281810.TAA00658@sable.ox.ac.uk>
Comments: Authenticated sender is <mert0407 AT sable DOT ox DOT ac DOT uk>
From: George Foot <george DOT foot AT merton DOT oxford DOT ac DOT uk>
To: ultrastar AT online DOT tietokone DOT fi (Niki Ruusunko)
Date: Tue, 28 Jul 1998 19:09:51 +0000
MIME-Version: 1.0
Subject: Re: sprintf and 64 bit integers
Reply-to: george DOT foot AT merton DOT oxford DOT ac DOT uk
CC: djgpp AT delorie DOT com

On 28 Jul 98 at 18:43, Niki Ruusunko wrote:

> I have this problem with a function I use to do thousands separators to
> integers. Here is the code:

[snipped]

> It isn't very good function but it works (on ints that is). The problem is
> that I need it to support the "long long" -variables I use. Sprintf doesn't
> compile with a long long as the argument (it says: "warning: int format,
> different type arg (arg 3)") so I'm asking if there is an alternate
> function to make a string out of an int (or, a long long in this case).

According to the docs ("info libc a printf"), you can use the `L' or `ll' 
conversion qualifiers to specify long long integers, i.e.:

    sprintf (s, "%lld %Ld", x, x);

where x is a long long and s is a pointer to some chars; this should 
print the same number twice.

> Of course, if you know how to make the separators some better way, please
> tell me.

This is shorter:

    void go (unsigned long long x)
    {
        if (x / 1000) {
            go (x / 1000);
            printf (",%03d", (int)(x % 1000));
        } else {
            printf ("%d", (int)(x % 1000));
        }
    }

If you want it to print to memory instead, try this: (untested)

    char *go (unsigned long long x, char *s)
    {
        char *retval = s;
        if (x / 1000) {
            go (x / 1000, s);
            while (*s) s++;
            sprintf (s, ",%03d", (int)(x % 1000));
        } else {
            sprintf (s, "%d", (int)(x % 1000));
        }
        return retval;
    }

Make sure the buffer you pass is large enough.  Like many string 
functions, it returns the pointer you pass.

-- 
george DOT foot AT merton DOT oxford DOT ac DOT uk

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019