This ought to work. It uses a static array to store the results, so you'll need to arrange for these to be copied elsewhere if you don't want them to be clobbered by the next call.
该算法非常简单。它只使用长除法将数字重复除以10,然后在每次迭代时使用余数来构建文本输出。我假设输入由5个字节的字节序组成。通过更改的值,您可以轻松地将此值更改为使用更大的数字BIG_WORD_LENGTH
。我还应该指出,该函数根本无法使用负数。您可以通过在n达到零时脱离主循环来加快速度。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define BIG_WORD_LENGTH 5
// Length of output is at most ceil(BIG_WORD_LENGTH * log(256) / log(10))
// The following is a slight overestimate, but close enough
#define BIG_WORD_STRLEN (3 + (BIG_WORD_LENGTH) * 5 / 2)
typedef uint8_t big_word[BIG_WORD_LENGTH];
char *big_word_2_str(big_word num) {
// Make a local copy of the number
big_word n;
for (int i=0; i<BIG_WORD_LENGTH; i++) {
n[i] = num[i];
}
// Result goes here
static char result[BIG_WORD_STRLEN];
int p = BIG_WORD_STRLEN-1;
result[p--] = '\0';
// Calculate digits in base 10
for (int i=1; i<BIG_WORD_STRLEN; i++) {
int x, tmp = 0;
for (int j=0; j<BIG_WORD_LENGTH; j++) {
x = n[j];
x += tmp << 8;
tmp = x % 10;
n[j] = x / 10;
}
result[p--] = '0' + tmp;
}
// Trim leading zeros
while (++p < BIG_WORD_STRLEN-2 && result[p] == '0');
return result + p;
}
// Test:
int main() {
// 0x492559f64f = 314159265359
big_word x = { 0x49, 0x25, 0x59, 0xf6, 0x4f };
puts(big_word_2_str(x));
return 0;
}
如果只有32位整数,则可能也只有C89。我建议将变量向上移动。
很好,但是我将实现细节留给OP。毕竟,我们甚至还不知道这个38位数字的字节序。