This function encodes a 32-bit input value using characters from the
basic character set. It returns a pointer to a 6 character buffer which
contains an encoded version of n. To encode a series of bytes the
user must copy the returned string to a destination buffer. It returns
the empty string if n is zero, which is somewhat bizarre but
mandated by the standard.
Warning: Since a static buffer is used this function should not
be used in multi-threaded programs. There is no thread-safe alternative
to this function in the C library.
Compatibility Note: The XPG standard states that the return
value of l64a
is undefined if n is negative. In the GNU
implementation, l64a
treats its argument as unsigned, so it will
return a sensible encoding for any nonzero n; however, portable
programs should not rely on this.
To encode a large buffer l64a
must be called in a loop, once for
each 32-bit word of the buffer. For example, one could do something
like this:
char *
encode (const void *buf, size_t len)
{
/* We know in advance how long the buffer has to be. */
unsigned char *in = (unsigned char *) buf;
char *out = malloc (6 + ((len + 3) / 4) * 6 + 1);
char *cp = out;
/* Encode the length. */
/* Using `htonl' is necessary so that the data can be
decoded even on machines with different byte order. */
cp = mempcpy (cp, l64a (htonl (len)), 6);
while (len > 3)
{
unsigned long int n = *in++;
n = (n << 8) | *in++;
n = (n << 8) | *in++;
n = (n << 8) | *in++;
len -= 4;
if (n)
cp = mempcpy (cp, l64a (htonl (n)), 6);
else
/* `l64a' returns the empty string for n==0, so we
must generate its encoding ("......") by hand. */
cp = stpcpy (cp, "......");
}
if (len > 0)
{
unsigned long int n = *in++;
if (--len > 0)
{
n = (n << 8) | *in++;
if (--len > 0)
n = (n << 8) | *in;
}
memcpy (cp, l64a (htonl (n)), 6);
cp += 6;
}
*cp = '\0';
return out;
}
It is strange that the library does not provide the complete
functionality needed but so be it.