gpt4 book ai didi

ios - 如何将十六进制值转换为 NSString?

转载 作者:行者123 更新时间:2023-11-28 22:34:50 25 4
gpt4 key购买 nike

我有以下代码将十六进制值转换为相应的 nsstring 但它对我不起作用

NSMutableString * newString = [[NSMutableString alloc] init];
NSString *string=@"5c 57 c7 25 d9 57 b9 4c";
NSScanner *scanner = [[NSScanner alloc] initWithString:string];
unsigned value;
while([scanner scanHexInt:&value]) {
[newString appendFormat:@"%c",(char)(value & 0xFF)];
}
string = [newString copy];
NSLog(@"%@",string);

请帮帮我

最佳答案

一旦这样尝试,

- (NSString *) stringFromHex:(NSString *)str 
{
NSMutableData *stringData = [[NSMutableData alloc] init] ;
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
int i;
for (i=0; i < [str length] / 2; i++) {
byte_chars[0] = [str characterAtIndex:i*2];
byte_chars[1] = [str characterAtIndex:i*2+1];
whole_byte = strtol(byte_chars, NULL, 16);
[stringData appendBytes:&whole_byte length:1];
}

return [[NSString alloc] initWithData:stringData encoding:NSASCIIStringEncoding] ;
}

这样调用,

NSString* string = [self stringFromHex:@"5c 57 c7 25 d9 57 b9 4c"];
NSLog(@"%@",string);

关于ios - 如何将十六进制值转换为 NSString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16396547/

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