对于objc / cocoa有什么类似Python的unhexlify
吗?
>>> 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]'
答案 0 :(得分:3)
编辑:我没有理解unhexlify的作用。我仍然不清楚为什么它可能有用(评论者?)。
您必须一次挑选两个十六进制字符,将它们转换为int,然后吐出字符。
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是一个单行,他们都可以做大致相同的事情。
答案 1 :(得分: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 |..#.]|
编辑:
当然可以在unhexlify
模块的实际Python源代码中找到更强大的Python binascii
示例,可以查看here。查看to_int()
和binascii_unhexlify()
函数。
答案 2 :(得分:0)
strtol
功能怎么样?
它是这样的:
NSString * abc = @"abc";
NSInteger intVal = strtol([abc cStringUsingEncoding:NSASCIIStringEncoding], nil, 16);
NSLog(@"%lld", intVal);
//prints 2748