如何在不使用库的情况下将整数数组转换为字符串 [英] How to convert an integer array to a string without the use of a library

查看:95
本文介绍了如何在不使用库的情况下将整数数组转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在实习项目.

我必须开发一个整个系统,该系统将收集一些数据,然后将其发送到服务器.该系统由MSP430G2553微控制器组成,因此我使用纯C语言进行编码,而没有任何库,因此无法使用sprintf或malloc函数.

I have to develop a whole system that will gather some data and will then send it through to a server. The system consist of an MSP430G2553 microcontroller so I am coding in pure C without any library's, so no sprintf or malloc functions I can use.

此刻我遇到的问题是我不知道如何将数组中的所有数据立即发送到服务器.

The problem that I am having at the moment is that I have no idea how I am going to send all the data that is in an array to the server at once.

我有一个数组ADCvalue [20],其中包含20个值,范围从0-350

I have the array ADCvalue[20] with 20 values, ranging from 0-350

ADCvalue[20]= {10, 40, 50, 90, 100, 200, 300, 240, 260, 10, 40, 50, 90, 100, 200, 300, 240, 260, 300, 20}.

现在,我希望使用每个值之间的定界符,"一次将所有这些值发送到服务器. 像这样:

Now I want to send these values all at once with the delimiter "," between every value to the server. Like this:

10,40,50,90,100,200,300,240,260,10,40,50,90,100,200,300,240,260,300,20

如何获得这样的数组并立即发送通过?我已经有一个可以发送例如char property[] = "property"作为字符串的打印功能.

How can I get the array like this and send it through at once? I already have a print function that can send for example: char property[] = "property" as a string.

如果有人可以帮助我提供一些伪代码或一些算法来帮助我入门,那就太好了.

It would be great if somebody could help me with some psuedo code or some algorithmes to get me started.

推荐答案

正如您所述(出于某种原因)不使用任何库,我只是编写了一个简单的writeIntValue函数.请参见下面的代码,该代码使用此函数将正整数值序列写入字符数组. 希望对您有所帮助.

As you stated not to use any library (for whatever reason), I just wrote a simple writeIntValue-function. See the following code which uses this function to write a sequence of positive integral values into a character array. Hope it helps.

char* writeIntValue(int val, char* dest) {
    // count digits:
    int digits = 0;
    int valCopy = val;
    while (valCopy) {
        digits++;
        valCopy /= 10;
    }

    if (digits == 0)  // means val has been 0
        digits=1; // assume 1 digit to write the '0'-value

    for (int i=digits-1; i>=0; i--) {
        dest[i] = val%10 + '0';
        val/=10;
    }
    dest[digits] = '\0'; // write string-terminating 0x0-value
    return dest + digits; // return a pointer to the end of the value written so far
}

int main() {

    int ADCvalue[20]= {10, 40, 50, 90, 100, 200, 300, 240, 260, 10, 40, 50, 90, 100, 200, 300, 240, 260, 300, 20};

    char buffer[500] = { '\0' };
    char *dest = buffer;
    for (int i=0; i<20; i++) {
        if (i>0)
            *dest++ = ',';
        dest = writeIntValue(ADCvalue[i], dest);
    }
    // buffer here will be "10,40,50,90,100,200,300,240,260,10,40,50,90,100,200,300,240,260,300,20"
    return 0;
}

这篇关于如何在不使用库的情况下将整数数组转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆