我正在尝试使用 BEncoding ObjC class解码 .torrent
文件。
NSData *rawdata = [NSData dataWithContentsOfFile:@"/path/to/the.torrent"];
NSData *torrent = [BEncoding objectFromEncodedData:rawdata];
当我 NSLog
torrent
我得到以下信息:
{
announce = <68747470 3a2f2f74 6f727265 6e742e75 62756e74 752e636f 6d3a3639 36392f61 6e6e6f75 6e6365>;
comment = <5562756e 74752043 44207265 6c656173 65732e75 62756e74 752e636f 6d>;
"creation date" = 1225365524;
info = {
length = 732766208;
name = <7562756e 74752d38 2e31302d 6465736b 746f702d 69333836 2e69736f>;
"piece length" = 524288;
....
如何将 name
转换为 NSString?我试过了。。
NSData *info = [torrent valueForKey:@"info"];
NSData *name = [info valueForKey:@"name"];
unsigned char aBuffer[[name length]];
[name getBytes:aBuffer length:[name length]];
NSLog(@"File name: %s", aBuffer);
..它检索数据,但后面似乎有额外的 unicode 垃圾:
File name: ubuntu-8.10-desktop-i386.iso)
我也试过 (from here)..
NSString *secondtry = [NSString stringWithCharacters:[name bytes] length:[name length] / sizeof(unichar)];
..但这似乎返回了一堆随机字符:
扵湵畴㠭ㄮⴰ敤歳潴⵰㍩㘸椮潳
第一种方式(如 Apple 文档中所述)正确返回大部分数据的事实,以及一些额外的字节让我认为这可能是 BEncoding 库中的一个错误。但我对 ObjC 的了解更多可能有错。。
最佳答案
我认为这是应该重新强调的重要一点。原来,
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
不一样,
NSString *content = [[NSString alloc] initWithBytes:[responseData bytes]
length:[responseData length] encoding: NSUTF8StringEncoding];
第一个需要一个 NULL 终止的字节字符串,第二个不需要。在上述两种情况下,如果字节字符串未正确终止,则第一个示例中的 content
将为 NULL。
关于objective-c - 将 NSData 字节转换为 NSString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/550405/