|
1 | 1 |
|
2 | 2 | /**
|
3 | 3 | * @file
|
4 |
| - * @brief Convert integer to string (non-standard function) |
| 4 | + * @brief Convert a positive integer to string (non-standard function) |
| 5 | + * representation. |
5 | 6 | */
|
6 | 7 | #include <assert.h>
|
| 8 | +#include <inttypes.h> |
7 | 9 | #include <stdio.h>
|
8 | 10 | #include <stdlib.h>
|
9 | 11 | #include <string.h>
|
|
13 | 15 | * Converts an integer value to a null-terminated string using the specified
|
14 | 16 | * base and stores the result in the array given by str parameter.
|
15 | 17 | * @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 |
17 | 19 | * string.
|
18 | 20 | * @param base Numerical base used to represent the value as a string, between 2
|
19 | 21 | * and 16, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary.
|
20 | 22 | * @returns A pointer to the resulting null-terminated string, same as parameter
|
21 | 23 | * str.
|
| 24 | + * @note The destination array must be pre-allocated by the calling function. |
22 | 25 | */
|
23 |
| -char *int_to_string(int value, char dest[], int base) |
| 26 | +char *int_to_string(uint16_t value, char *dest, int base) |
24 | 27 | {
|
25 | 28 | const char hex_table[] = {'0', '1', '2', '3', '4', '5', '6', '7',
|
26 | 29 | '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
|
@@ -57,14 +60,14 @@ static void test()
|
57 | 60 | /* Generate value from 0 to 100 */
|
58 | 61 | int value = rand() % 100;
|
59 | 62 |
|
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); |
68 | 71 |
|
69 | 72 | free(str1);
|
70 | 73 | free(str2);
|
|
0 commit comments