Skip to content

Commit 313a980

Browse files
int_to_string
1 parent ff2e7a3 commit 313a980

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

conversions/int_to_string.c

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
2+
/**
3+
* @file
4+
* @brief Convert integer to string (non-standard function)
5+
*/
6+
#include <assert.h>
7+
#include <stdio.h>
8+
#include <stdlib.h>
9+
#include <string.h>
10+
#include <time.h>
11+
12+
/**
13+
* Converts an integer value to a null-terminated string using the specified
14+
* base and stores the result in the array given by str parameter.
15+
* @param value Value to be converted to a string.
16+
* @param dest Array in memory where to store the resulting null-terminated
17+
* string.
18+
* @param base Numerical base used to represent the value as a string, between 2
19+
* and 16, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary.
20+
* @returns A pointer to the resulting null-terminated string, same as parameter
21+
* str.
22+
*/
23+
char *int_to_string(int value, char dest[], int base)
24+
{
25+
const char hex_table[] = {'0', '1', '2', '3', '4', '5', '6', '7',
26+
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
27+
28+
int len = 0;
29+
do
30+
{
31+
dest[len++] = hex_table[value % base];
32+
value /= base;
33+
} while (value != 0);
34+
35+
/* reverse characters */
36+
for (int i = 0, limit = len / 2; i < limit; ++i)
37+
{
38+
char t = dest[i];
39+
dest[i] = dest[len - 1 - i];
40+
dest[len - 1 - i] = t;
41+
}
42+
dest[len] = '\0';
43+
return dest;
44+
}
45+
46+
/** Test function
47+
* @returns `void`
48+
*/
49+
static void test()
50+
{
51+
const int MAX_SIZE = 100;
52+
for (int i = 1; i <= 100; ++i)
53+
{
54+
char *str1 = (char *)calloc(sizeof(char), MAX_SIZE);
55+
char *str2 = (char *)calloc(sizeof(char), MAX_SIZE);
56+
57+
/* Generate value from 0 to 100 */
58+
int value = rand() % 100;
59+
60+
assert(strcmp(itoa(value, str1, 2), int_to_string(value, str2, 2)) ==
61+
0);
62+
assert(strcmp(itoa(value, str1, 8), int_to_string(value, str2, 8)) ==
63+
0);
64+
assert(strcmp(itoa(value, str1, 10), int_to_string(value, str2, 10)) ==
65+
0);
66+
assert(strcmp(itoa(value, str1, 16), int_to_string(value, str2, 16)) ==
67+
0);
68+
69+
free(str1);
70+
free(str2);
71+
}
72+
}
73+
74+
/** Driver Code */
75+
int main()
76+
{
77+
/* Intializes random number generator */
78+
srand(time(NULL));
79+
test();
80+
return 0;
81+
}

0 commit comments

Comments
 (0)