I want to convert an integer into a string of numeric characters in C.
I've tried using itoa
, but it's non-standard and not provided by my C library.
I tried to implement my own itoa
, but it's not working properly:
#include <stdlib.h>
#include <stdio.h>
char *itoa(int val, char *buf, int base)
{
size_t ctr = 0;
for( ; val; val /= base )
{
buf[ctr++] = '0' + (val % base);
}
buf[ctr] = 0;
return buf;
}
int main(void)
{
unsigned char c = 201;
char *buf = malloc(sizeof(c)*8+1);
itoa(c, buf, 2);
puts(buf);
free(buf);
}
It gives reversed output.
For example, if c
is 'A'
and base
is 2
, the output is this: 0101101
The output I want it to be is this: 1011010
How do I fix this issue?
Similar questions
I've already seen this question: Is there a printf converter to print in binary format?
I do not want a printf
format specifier to print an integer as binary, I want to convert the binary to a string.
I've already seen this question: Print an int in binary representation using C
Although the answer does convert an integer into a string of binary digits, that's the only thing it can do.
Restrictions
I want itoa
to be able to work with other base
s, such as 10
, 8
, etc. and print correctly (i.e. 12345
translates to "12345"
and not to "11000000111001"
).
I do not want to use printf
or sprintf
to do this.
I do not care about the length of the string as long is the result is correct.
I do not want to convert the integer into ASCII characters other than numeric ones, with the exception of base
s greater than 10, in which case the characters may be alphanumeric.
The answer must fit this prototype exactly:
char *itoa(int val, char *buf, int base);
There may be a function called nitoa
that has this prototype and returns the number of characters required to hold the result of itoa
:
size_t nitoa(int val, int base);
sprintf()
instead ofprintf()
and it will write to a string. – Mandorlasprintf
orprintf
, and anyway, those don't deal with binary. – Kollwitz