首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C中Python的binascii.unhexlify函数

C中Python的binascii.unhexlify函数
EN

Stack Overflow用户
提问于 2018-03-06 15:17:31
回答 1查看 1.3K关注 0票数 1

我正在构建一个程序,它接受输入,就好像它是一个空的MAC地址,并将它转换成二进制字符串。我是在嵌入式系统上这样做的,所以没有性病。我一直在尝试类似于this question的东西,但两天后我什么也没有实现,我对这类事情做得很糟糕。

我想要的是产出等于目标,考虑到这一点:

代码语言:javascript
复制
#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");
    }
}

谢谢,这是个私人项目,我真的很想完成

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-06 15:29:32

首先,您的比较应该使用strcmp,否则总是错误的。

然后,我将读取字符串2-char乘以2-char,并将每个“数字”转换为其值(0-15),然后用移位的方式组成结果。

代码语言:javascript
复制
#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");
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49134190

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档