gpt4 book ai didi

php - 在 Objective-C 中将十六进制字符串转换为二进制

转载 作者:行者123 更新时间:2023-12-03 16:58:52 25 4
gpt4 key购买 nike

PHP 函数 pack 的等效项是什么:

pack('H*', '01234567989abcdef' );

在 Objective-C 中?

最佳答案

假设您希望将结果作为 NSData,您可以使用与此类似的函数:

NSData *CreateDataWithHexString(NSString *inputString)
{
NSUInteger inLength = [inputString length];

unichar *inCharacters = alloca(sizeof(unichar) * inLength);
[inputString getCharacters:inCharacters range:NSMakeRange(0, inLength)];

UInt8 *outBytes = malloc(sizeof(UInt8) * ((inLength / 2) + 1));

NSInteger i, o = 0;
UInt8 outByte = 0;
for (i = 0; i < inLength; i++) {
UInt8 c = inCharacters[i];
SInt8 value = -1;

if (c >= '0' && c <= '9') value = (c - '0');
else if (c >= 'A' && c <= 'F') value = 10 + (c - 'A');
else if (c >= 'a' && c <= 'f') value = 10 + (c - 'a');

if (value >= 0) {
if (i % 2 == 1) {
outBytes[o++] = (outByte << 4) | value;
outByte = 0;
} else if (i == (inLength - 1)) {
outBytes[o++] = value << 4;
} else {
outByte = value;
}

} else {
if (o != 0) break;
}
}

return [[NSData alloc] initWithBytesNoCopy:outBytes length:o freeWhenDone:YES];
}

关于php - 在 Objective-C 中将十六进制字符串转换为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8950644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com