基本上,下面的代码将导致串联的字符串放置在“ dec”中。通过下面的代码行的函数读取的内存为101E34,即“ dec”应转换为163052。如何转换该字符串?
for (int j = 0; j <2; j++)
{
char temp[100]= "";
sprintf(temp, "%x", readArray[j]);
if (strlen(temp) < 4)
{
char dec[100] = "";
for (int r = 0; r < 4 - strlen(temp); r++)
{
strcat(dec,"0");
}
strcat(dec, temp);
}
}
答案 0 :(得分:-1)
#include <stdio.h>
int main() {
char input[] = "101E34";
char output[100];
int i = 0, j = 0, k = 0;
for(i = 0; i < 6;) {
if(input[i] >= '0' && input[i] <= '9')
j = (input[i] - '0')<< 4;
else if(input[i] >= 'A' && input[i] <= 'Z')
j = (input[i] - 'A' + 10)<< 4;
else if(input[i] >= 'a' && input[i] <= 'z')
j = (input[i] - 'a' + 10)<< 4;
if(input[i + 1] >= '0' && input[i + 1] <= '9')
j = j + (input[i + 1] - '0');
else if(input[i + 1] >= 'A' && input[i + 1] <= 'Z')
j = j + (input[i + 1] - 'A' + 10);
else if(input[i + 1] >= 'a' && input[i + 1] <= 'z')
j = j + (input[i + 1] - 'a' + 10);
k += snprintf((output + k), (100 - k), "%d", j);
i = i + 2;
}
puts(output);
return 0;
}
唯一的限制是output
的大小。如果input
大或每次运行都发生变化,则可能需要动态分配它。