|
发表于 2013-2-6 15:40:28
|
显示全部楼层
本帖最后由 takashiki 于 2013-2-6 15:43 编辑
侧重效率的算法
刚才自己稍微算了一下,32位的乘法以及移位效率也不高,还不如直接辗转相减呢。总的时间占用没有详细计算,只提供方案如下,占用Flash很大的。假设输入的为long Input,输出为char temp[9]。temp[8]总是为0,以便于字符串的计算。- char temp[9];
- void LongToStr(long Input){ //针对你这个具体项目进行计算
- char c; //目的是尽量使编译器使用寄存器而不是变量,因为AVR的内存访问效率较低。
- unsigned short wordInput;
- unsigned char bytInput;
-
- c = '0'; //计算最高位
- if(Input >= 8000000) c += 8, Input -= 8000000;
- if(Input >= 4000000) c += 4, Input -= 4000000;
- if(Input >= 2000000) c += 2, Input -= 2000000;
- if(Input >= 1000000) c += 1, Input -= 1000000;
- temp[0] = c;
-
- c = '0'; //计算第二位
- if(Input >= 800000) c += 8, Input -= 800000;
- if(Input >= 400000) c += 4, Input -= 400000;
- if(Input >= 200000) c += 2, Input -= 200000;
- if(Input >= 100000) c += 1, Input -= 100000;
- temp[1] = c;
-
- c = '0';
- if(Input >= 80000) c += 8, Input -= 80000;
- if(Input >= 40000) c += 4, Input -= 40000;
-
- //到这里为止,Input一定小于40000,因此可以采用short类型了!
- wordInput = (unsigned short)Input;
- if(wordInput >= 20000) c += 2, wordInput -= 20000;
- if(wordInput >= 10000) c += 1, wordInput -= 10000;
- temp[2] = c;
-
- c = '0';
- if(wordInput >= 8000) c += 8, wordInput -= 8000;
- if(wordInput >= 4000) c += 4, wordInput -= 4000;
- if(wordInput >= 2000) c += 2, wordInput -= 2000;
- if(wordInput >= 1000) c += 1, wordInput -= 1000;
- temp[3] = c;
-
- temp[4] = (wordInput * 205u) >> 11;
- bytInput = wordInput - temp[4] * 10;
-
- temp[5] = (unsigned char)((bytInput * 205u)>>8) >> 3;
- bytInput = wordInput - temp[5] * 10;
-
- temp[6] = (unsigned char)((bytInput * 205u)>>8) >> 3;
- temp[7] = wordInput - temp[6] * 10;
- temp[8] = 0;
- }
复制代码 后面的<1000的计算参见我的一个帖子:AVR中除10的优化算法 |
|