Bytes to Decimal String
Last Update
- July 28 2024 - Initial commit
- Jan 17 2025 - Optimised
Introduction
I was assigned to write a function (in C) that converts an array of bytes into a decimal string. The 0-th index (first element) of the array is the most significant byte (MSB) and the last element in the array is the least significant byte (LSB). The length of the array could grow up to 32 bytes. The usual multiply by 256 and carry over method from the LSB will definitely cause the stack overflow.
The Code in C
void bytes_to_dec_string(uint8_t *bytes, uint8_t length, char *output) { if (length > 32 || length <= 0 || bytes == NULL || output == NULL) return; uint8_t i = 0, j = 0, k = 0; uint8_t result[80] = {0}; uint32_t carry_over = 0UL; while (i < length && bytes[i] == 0) i++; while (i < length) { carry_over = bytes[i++]; j = 0; while (carry_over || j < k) { carry_over += result[j] * 256; result[j++] = carry_over % 10; carry_over /= 10; } k = j; } for (i = 0; i < k; i++) { output[i] = result[k - i - 1] + '0'; } output[k] = '\0'; }