优化代码 #include <stdio.h> #include <string.h> unsigned char srec[] = {"S00600004844521B" "S1130000285F245F2212226A000424290008237C2A" "S11300100002000800082629001853812341001813" "S113002041E900084E42234300182342000824A952" "S107003000144ED492" "S5030004F8" "S9030000FC"}; int hex_to_int(unsigned char *hex, int len) { int res = 0; for (int i = 0; i < len; i++) { res <<= 4; if (hex[i] >= '0' && hex[i] <= '9') { res += hex[i] - '0'; } else if (hex[i] >= 'A' && hex[i] <= 'F') { res += hex[i] - 'A' + 10; } else if (hex[i] >= 'a' && hex[i] <= 'f') { res += hex[i] - 'a' + 10; } } return res; } void convert(unsigned char *pSrec, unsigned char *pData) { int i, j = 0; unsigned char data[256]; // 遍历.S19文件内容 for (i = 0; pSrec[i] != '\0'; i += 2) { // 如果是S1记录 if (pSrec[i] == 'S' && pSrec[i + 1] == '1') { // 获取数据字节数和地址 int count = hex_to_int(pSrec + i + 2, 2); int address = hex_to_int(pSrec + i + 4, 4); // 将数据存入pData中 for (int k = 0; k < count - 3; k++) { pData[j] = hex_to_int(pSrec + i + 8 + k * 2, 2); j++; } } } } int main() { unsigned char data[256]; convert(srec, data); for (int i = 0; i < 64; i++) { printf("%02X ", data[i]); } printf("\n"); return 0; }
时间: 2024-03-27 16:35:31 浏览: 58
C标准库函数集
5星 · 资源好评率100%
这段代码可以通过使用位运算代替位移运算和使用更好的变量名来进行优化,例如:
```
#include <stdio.h>
#include <string.h>
unsigned char srec[] = {"S00600004844521B"
"S1130000285F245F2212226A000424290008237C2A"
"S11300100002000800082629001853812341001813"
"S113002041E900084E42234300182342000824A952"
"S107003000144ED492"
"S5030004F8"
"S9030000FC"};
int hex_to_int(unsigned char *hex, int len) {
int res = 0;
for (int i = 0; i < len; i++) {
res <<= 4;
if (hex[i] >= '0' && hex[i] <= '9') {
res += hex[i] - '0';
} else if (hex[i] >= 'A' && hex[i] <= 'F') {
res += hex[i] - 'A' + 10;
} else if (hex[i] >= 'a' && hex[i] <= 'f') {
res += hex[i] - 'a' + 10;
}
}
return res;
}
void convert(unsigned char *srec, unsigned char *data) {
int j = 0;
// 遍历.S19文件内容
for (int i = 0; srec[i] != '\0'; i += 2) {
// 如果是S1记录
if (srec[i] == 'S' && srec[i + 1] == '1') {
// 获取数据字节数和地址
int count = hex_to_int(srec + i + 2, 2);
int address = hex_to_int(srec + i + 4, 4);
// 将数据存入data中
for (int k = 0; k < count - 3; k++) {
data[j++] = hex_to_int(srec + i + 8 + k * 2, 2);
}
}
}
}
int main() {
unsigned char data[256];
convert(srec, data);
for (int i = 0; i < 64; i++) {
printf("%02X ", data[i]);
}
printf("\n");
return 0;
}
```
此外,如果这段代码需要被优化以提高性能,可以使用更快的算法来处理十六进制字符串转整数的过程,例如使用查表法或者使用更快的位运算。
阅读全文