温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - How to convert 32+ bit number (38bit) into a string on a 32bit system, smartly in C
c

其他 - 如何在C语言中巧妙地将32位以上的位数(38位)转换为32位系统上的字符串

发布于 2020-03-28 23:42:03

如果最大的可用数据格式是32位,您将如何将38位数字转换为字符串?

需要十进制表示,需要字符串以将数字保存到csv文件中。

The question is complete "as is", there is no need to look for the perceived true intention of the question elsewhere.

查看更多

查看更多

提问者
Horst
被浏览
20
r3mainer 2020-01-31 20:36

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;
}