Objective C中的unhexlify

2 投票
3 回答
1303 浏览
提问于 2025-04-15 16:48

有没有类似于Python中unhexlify的东西可以在objc / cocoa中使用?

>>> from binascii import unhexlify
>>> help(unhexlify)
Help on built-in function unhexlify in module binascii:

unhexlify(...)
a2b_hex(hexstr) -> s; Binary data of hexadecimal representation.

hexstr must contain an even number of hex digits (upper or lower case).
This function is also available as "unhexlify()"

>>> unhexlify('abc123d35d')
'\xab\xc1#\xd3]'

3 个回答

0

那我们来看看 strtol 这个函数吧。

它的用法大概是这样的:

NSString * abc = @"abc";
NSInteger intVal = strtol([abc cStringUsingEncoding:NSASCIIStringEncoding], nil, 16);
NSLog(@"%lld", intVal);
//prints 2748
2

这里有一些非常粗糙、简单、效率低下且不安全的代码,它实现了 unhexlify 功能。它的主要问题是没有检查 hexstr 是否只包含十六进制数字。不过,这段代码应该能帮助你入门。

#include <stdio.h>
#include <string.h>
#include <assert.h>

void unhexlify(const char *hexstr, char *binstr)
{
    char *p, *q;

    assert(strlen(hexstr) > 0);
    assert(strlen(hexstr) % 2 == 0);    // even length

    for (p=hexstr,q=binstr; *p; p+=2,q++)
        sscanf(p, "%2x", q);
    *q = '\0';
}

int main()
{
    char *s = "abc123d35d";
    char buf[100];

    unhexlify(s, buf);
    printf(buf);
}

把这个文件命名为 unhexlify.c,然后运行这个程序:

$ ./unhexlify | hexdump -C
00000000  ab c1 23 d3 5d                                    |..#.]|

编辑: 更健壮的 Python 中 unhexlify 的例子可以在实际的 Python 源代码中找到,具体是在 binascii 模块里,你可以在 这里 查看。可以看看 to_int()binascii_unhexlify() 这两个函数。

3

编辑:我之前没搞明白unhexlify是干嘛的。现在我还是不太明白它有什么用(评论的人能解释一下吗?)。

你需要每次取两个十六进制字符,把它们转换成一个整数,然后输出对应的字符。

char *hex = "abc123d35d";

NSData *data = [NSData dataWithBytesNoCopy:hex length:strlen(hex)];

NSInputStream *input = [NSInputStream inputStreamWithWithData:data];
NSOutputStream *output = [NSOutputStream outputStreamToMemory];

[input open];
[output open];

uint8_t buffer[2], result;

while ([input hasBytesAvailable]) {
   [input read:buffer maxLength:2];

   if (sscanf(buffer, "%x", &result) != 1)
       // die

   if (![output hasSpaceAvailable])
       // die

   [output write:&result length:1];
}

[input close];
[output close];

id output = [output propertyForKey:NSStreamDataWrittenToMemoryStreamKey];

这个方法其实只有在你要处理大量数据的时候才会有用。

不过正如其他人所说的,可能还有更好的方法来实现你想做的事情,而不需要用到unhexlify。举个例子,虽然没有内置的方法来读取YAML文件,但读取plist文件只需要一行代码,而且它们大致能完成相同的功能。

撰写回答