十六进制字符串在C字节数组 [英] Hexadecimal string to byte array in C

查看:112
本文介绍了十六进制字符串在C字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有从十六进制字符串转换为字节数组任何标准的C函数?结果
我不想写我自己的功能。

Is there any standard C function that converts from hexadecimal string to byte array?
I do not want to write my own function.

推荐答案

据我所知,有没有标准功能这样做,但其实很简单通过以下方式来实现:

As far as I know, there's no standard function to do so, but it's simple to achieve in the following manner:

#include <stdio.h>

int main(int argc, char **argv)
{
    const char hexstring[] = "deadbeef10203040b00b1e50", *pos = hexstring;
    unsigned char val[12];
    size_t count = 0;

     /* WARNING: no sanitization or error-checking whatsoever */
    for(count = 0; count < sizeof(val)/sizeof(val[0]); count++) {
        sscanf(pos, "%2hhx", &val[count]);
        pos += 2;
    }

    printf("0x");
    for(count = 0; count < sizeof(val)/sizeof(val[0]); count++)
        printf("%02x", val[count]);
    printf("\n");

    return(0);
}

希望这有助于。

由于铝指出,在奇数的字符串中的十六进制数字的情况下,你必须确保你的起始0。例如preFIX它,字符串f00f5 将被评估为 {0XF0,为0x0F为0x05} 通过上面的例子错误,而不是正确的 {为0x0F ,为0x00,0xf5}

As Al pointed out, in case of an odd number of hex digits in the string, you have to make sure you prefix it with a starting 0. For example, the string "f00f5" will be evaluated as {0xf0, 0x0f, 0x05} erroneously by the above example, instead of the proper {0x0f, 0x00, 0xf5}.

这篇关于十六进制字符串在C字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆