我正在构建一个程序,它接受输入,就好像它是一个空的MAC地址,并将它转换成二进制字符串。我是在嵌入式系统上这样做的,所以没有性病。我一直在尝试类似于this question的东西,但两天后我什么也没有实现,我对这类事情做得很糟糕。
我想要的是产出等于目标,考虑到这一点:
#include <stdio.h>
int main() {
const char* goal = "\xaa\xbb\xcc\xdd\xee\xff";
printf("Goal: %s\n", goal);
char* input = "aabbccddeeff";
printf("Input: %s\n", input);
char* output = NULL;
// Magic code here
if (output == goal) {
printf("Did work! Yay!");
} else {
printf("Did not work, keep trying");
}
}谢谢,这是个私人项目,我真的很想完成
发布于 2018-03-06 15:29:32
首先,您的比较应该使用strcmp,否则总是错误的。
然后,我将读取字符串2-char乘以2-char,并将每个“数字”转换为其值(0-15),然后用移位的方式组成结果。
#include <stdio.h>
#include <string.h>
// helper function to convert a char 0-9 or a-f to its decimal value (0-16)
// if something else is passed returns 0...
int a2v(char c)
{
if ((c>='0')&&(c<='9'))
{
return c-'0';
}
if ((c>='a')&&(c<='f'))
{
return c-'a'+10;
}
else return 0;
}
int main() {
const char* goal = "\xaa\xbb\xcc\xdd\xee\xff";
printf("Goal: %s\n", goal);
const char* input = "aabbccddeeff";
int i;
char output[strlen(input)/2 + 1];
char *ptr = output;
for (i=0;i<strlen(input);i+=2)
{
*ptr++ = (a2v(input[i])<<4) + a2v(input[i]);
}
*ptr = '\0';
printf("Goal: %s\n", output);
if (strcmp(output,goal)==0) {
printf("Did work! Yay!");
} else {
printf("Did not work, keep trying");
}
}https://stackoverflow.com/questions/49134190
复制相似问题