C89/POSIX-compliant conversion library from integers to strings that supports various signed and unsigned integer number bases and bit-widths.
#include <stdlib.h>
#include <stdio.h>
#include <its.h>
int
main(void)
{
int a;
char* a_str;
a = -123;
a_str = its(&a, ITS_SIZE_INT, ITS_SIGNED, ITS_BASE_HEX | ITS_PREFIX);
printf("%s\n", a_str);
free(a_str);
return EXIT_SUCCESS;
}
Compile & run:
$ clang example.c -lits
$ ./a.out
-0x7b
- Binary base
- Signed hexadecimal and octal numbers up to
(U)INT_MAX
- Correct handling of arbitrary bit-sized integers
- It is a (yet another) dependency
- Not standard
- More verbose usage
For such features, the printf
alternative is the solution. But instead of
%lld
or any related format, use the %s
format with value of a its
call.
$ ninja
The library is working quite heavily with the two-complement format of signed integers, which is one of the three signed number representations allowed by the C89 standard and the only representation allowed in the POSIX family of standards.
- FreeBSD 10.0 with Clang 3.3
If a platform does not appear to be in the previous list, it does not mean that
libits
will not work in such environment. It only means that nobody tested
it - you are encouraged to do so and report either success or failure.
2-clause BSD license. For more information please consult the LICENSE file. In the case that you need a different license, feel free to contact me.
Daniel Lovasko lovasko@freebsd.org