patterncMinor
itoa base function in C
Viewed 0 times
basefunctionitoa
Problem
This is a function that converts an integer value to a null-terminated string using the specified base and stores the result in a
char array that I must allocate (with malloc). I have decided not to use malloc. Allowed functions: malloc. Loops: while Please review my code.char *itoa_base(int value, int base)
{
static char rep[] = "0123456789abcdef";
static char buf[50];
char *ptr;
int num;
ptr = &buf[49];
*ptr = '\0';
num = value;
if (value < 0 && base == 10)
value *= -1;
if (value == 0)
*--ptr = rep[value % base];
while (value != 0)
{
*--ptr = rep[value % base];
value /= base;
}
if (num < 0 && base == 10)
*--ptr = '-';
return (ptr);Solution
Input checking
Insufficient buffer size
On a system with 64-bit ints and a base of 2, you will need a buffer of size 65 instead of 50. (Or 66 if you allow negative values for all bases).
Code simplification
This code:
could be simplified to:
I'm not sure from your question whether you were allowed to use a
- If the caller passes in a
basegreater than 17, you will read past the end ofrep.
- If the caller passes in a
baseof 0, you will divide by zero.
- If the caller passes in a
baseof 1, your code will infinite loop.
- If the caller passes in a negative
valuebut the base is not 10, you will read past the front ofrepbecause your modulus will be negative. You should always makevaluepositive before proceeding with your loop.
Insufficient buffer size
On a system with 64-bit ints and a base of 2, you will need a buffer of size 65 instead of 50. (Or 66 if you allow negative values for all bases).
Code simplification
This code:
if (value == 0)
*--ptr = rep[value % base];
while (value != 0)
{
*--ptr = rep[value % base];
value /= base;
}could be simplified to:
do {
*--ptr = rep[value % base];
value /= base;
} while (value != 0);I'm not sure from your question whether you were allowed to use a
do loop or not. Also, your question says you are supposed to return an allocated buffer but you intentionally didn't, so I'm not sure how to review that part of it.Code Snippets
if (value == 0)
*--ptr = rep[value % base];
while (value != 0)
{
*--ptr = rep[value % base];
value /= base;
}do {
*--ptr = rep[value % base];
value /= base;
} while (value != 0);Context
StackExchange Code Review Q#132591, answer score: 4
Revisions (0)
No revisions yet.