Skip to content

Commit 98f9ae3

Browse files
committed
replaced itoa with snprintf & fixed other docs
1 parent 313a980 commit 98f9ae3

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

conversions/int_to_string.c

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11

22
/**
33
* @file
4-
* @brief Convert integer to string (non-standard function)
4+
* @brief Convert a positive integer to string (non-standard function)
5+
* representation.
56
*/
67
#include <assert.h>
8+
#include <inttypes.h>
79
#include <stdio.h>
810
#include <stdlib.h>
911
#include <string.h>
@@ -13,14 +15,15 @@
1315
* Converts an integer value to a null-terminated string using the specified
1416
* base and stores the result in the array given by str parameter.
1517
* @param value Value to be converted to a string.
16-
* @param dest Array in memory where to store the resulting null-terminated
18+
* @param dest pointer to array in memory to store the resulting null-terminated
1719
* string.
1820
* @param base Numerical base used to represent the value as a string, between 2
1921
* and 16, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary.
2022
* @returns A pointer to the resulting null-terminated string, same as parameter
2123
* str.
24+
* @note The destination array must be pre-allocated by the calling function.
2225
*/
23-
char *int_to_string(int value, char dest[], int base)
26+
char *int_to_string(uint16_t value, char *dest, int base)
2427
{
2528
const char hex_table[] = {'0', '1', '2', '3', '4', '5', '6', '7',
2629
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
@@ -57,14 +60,14 @@ static void test()
5760
/* Generate value from 0 to 100 */
5861
int value = rand() % 100;
5962

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);
63+
// assert(strcmp(itoa(value, str1, 2), int_to_string(value, str2, 2)) ==
64+
// 0);
65+
snprintf(str1, MAX_SIZE, "%o", value);
66+
assert(strcmp(str1, int_to_string(value, str2, 8)) == 0);
67+
snprintf(str1, MAX_SIZE, "%d", value);
68+
assert(strcmp(str1, int_to_string(value, str2, 10)) == 0);
69+
snprintf(str1, MAX_SIZE, "%x", value);
70+
assert(strcmp(str1, int_to_string(value, str2, 16)) == 0);
6871

6972
free(str1);
7073
free(str2);

0 commit comments

Comments
 (0)