gpt4 book ai didi

ios - 将 HEX NSString 转换为 ASCII NSString

转载 作者:行者123 更新时间:2023-11-28 21:41:27 25 4
gpt4 key购买 nike

我得到一个包含十六进制值 的 NSString,我想将其转换为 ASCII。我该怎么做?

NSString * hexString = // some value
NSString * asciiString = // ? convert hexString to ASCI somehow

我尝试过的错误方法:

我尝试了以下在 similar question 上找到的方法但它对我不起作用:

   NSData *_data = [hexString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableString *_string = [NSMutableString stringWithString:@""];
for (int i = 0; i < _data.length; i++) {
unsigned char _byte;
[_data getBytes:&_byte range:NSMakeRange(i, 1)];
if (_byte >= 32 && _byte < 127) {
[_string appendFormat:@"%c", _byte];
} else {
[_string appendFormat:@"[%d]", _byte];
}
}
asciiString = _string; // Still shows the same as before..

最佳答案

这对我有用:

NSString * str = @"312d4555";
NSMutableString * newString = [[NSMutableString alloc] init];
int i = 0;
while (i < [str length]){
NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
int value = 0;

sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
[newString appendFormat:@"%c", (char)value];
i+=2;
}
NSLog(@"%@", newString);

输出是:你好

关于ios - 将 HEX NSString 转换为 ASCII NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31875002/

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