问题描述
使用微控制器(PIC18F4580),我需要收集数据并将其发送到供以后分析SD卡。它收集的数据将在0到1023,或0x0和0x3FF对之间的值。
Using a microcontroller (PIC18F4580), I need to collect data and send it to an SD card for later analysis. The data it collects will have values between 0 and 1023, or 0x0 and 0x3FF.
所以我需要做的是转换成1023字面ASCII值的基数为10串(0X31,为0x30,0x32,0x33,...)。
So what I need to do is convert 1023 into a base 10 string of literal ASCII values (0x31, 0x30, 0x32, 0x33, ...).
我的问题是我能想到的分裂位的相隔只有这样需要大量的分工。
My problem is that the only way I can think of to split the digits apart requires a lot of division.
char temp[4];
temp[0] = 1023 % 10;
temp[1] = (1023 % 100) / 10;
temp[2] = (1023 % 1000) / 100;
temp[3] = (1023 % 10000) / 1000;
使用这种方法,发现在n位十进制数的ASCII值需要2n-1个区划。是否有会更快的方法?
Using this method, finding the ASCII values of an n digit decimal number requires 2n-1 divisions. Is there a method that would be faster?
这样做的最终目的是能够快速插入任何笔记本电脑来查看数据的Excel中的图表中的SD卡上的.csv文件拉闸。
The end goal of this is to wind up with a .csv file on the SD card that can quickly be plugged into any laptop to see a graph of the data in Excel.
推荐答案
有一个使用减法做的一种方式,但我不相信这是比使用一个正常的CPU减法和模快(可能处于不同嵌入式环境)。
There's a way of doing it using subtractions, but I am not convinced it's faster than using subtractions and modulus on a "normal" CPU (may be different in an embedded environment).
事情是这样的:
char makedigit (int *number, int base)
{
static char map[] = "0123456789";
int ix;
for (ix=0; *number >= base; ix++) { *number -= base; }
return map[ix];
}
char *makestring (int number)
{
static char tmp[5];
tmp[0] = makedigit(&number, 1000);
tmp[1] = makedigit(&number, 100);
tmp[2] = makedigit(&number, 10);
tmp[3] = makedigit(&number, 1);
tmp[5] = '\0';
return tmp;
}
然后,通话makestring()
应导致(静态的,所以覆盖前将它复制)与转换的数字串(零prefixed,在4个字符宽,作为原始假设是在0-1023范围内的值)。
Then, a call to makestring()
should result in a (static, so copy it before overwriting) string with the converted number (zero-prefixed, at 4 characters width, as the original assumption is a value in the 0-1023 range).
这篇关于转换为ASCII使用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!