Skip to content

Commit acb1c8a

Browse files
authored
new init int to string
1 parent 86cdfac commit acb1c8a

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Integer_to_string.c

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* @file
3+
* @brief Convert a positive integer to string (non-standard function)
4+
* representation.
5+
*/
6+
#include <assert.h>
7+
#include <inttypes.h>
8+
#include <stdio.h>
9+
#include <stdlib.h>
10+
#include <string.h>
11+
#include <time.h>
12+
13+
char *int_to_string(uint16_t value, char *dest, int base)
14+
{
15+
const char hex_table[] = {'0', '1', '2', '3', '4', '5', '6', '7',
16+
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
17+
18+
int len = 0;
19+
do
20+
{
21+
dest[len++] = hex_table[value % base];
22+
value /= base;
23+
} while (value != 0);
24+
25+
/* reverse characters */
26+
for (int i = 0, limit = len / 2; i < limit; ++i)
27+
{
28+
char t = dest[i];
29+
dest[i] = dest[len - 1 - i];
30+
dest[len - 1 - i] = t;
31+
}
32+
dest[len] = '\0';
33+
return dest;
34+
}
35+
36+
/** Test function
37+
* @returns `void`
38+
*/
39+
static void test()
40+
{
41+
const int MAX_SIZE = 100;
42+
char *str1 = (char *)calloc(sizeof(char), MAX_SIZE);
43+
char *str2 = (char *)calloc(sizeof(char), MAX_SIZE);
44+
45+
for (int i = 1; i <= 100; ++i) /* test 100 random numbers */
46+
{
47+
/* Generate value from 0 to 100 */
48+
int value = rand() % 100;
49+
50+
// assert(strcmp(itoa(value, str1, 2), int_to_string(value, str2, 2)) ==
51+
// 0);
52+
snprintf(str1, MAX_SIZE, "%o", value); //* standard C - to octal */
53+
assert(strcmp(str1, int_to_string(value, str2, 8)) == 0);
54+
snprintf(str1, MAX_SIZE, "%d", value); /* standard C - to decimal */
55+
assert(strcmp(str1, int_to_string(value, str2, 10)) == 0);
56+
snprintf(str1, MAX_SIZE, "%x", value); /* standard C - to hexadecimal */
57+
assert(strcmp(str1, int_to_string(value, str2, 16)) == 0);
58+
}
59+
60+
free(str1);
61+
free(str2);
62+
}
63+
64+
/** Driver Code */
65+
int main()
66+
{
67+
/* Intializes random number generator */
68+
srand(time(NULL));
69+
test();
70+
return 0;
71+
}

0 commit comments

Comments
 (0)