objective-c - 将 NSData 字节转换为 NSString?

标签 objective-c cocoa bittorrent

我正在尝试使用 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/

相关文章:

xcode - 列出 iCloud 中可用的文件

objective-c - 使用 Cocoa/objective-C 从整数(年 ... 秒)构建 NSDate

p2p - 在像 bittorrent 这样的点对点协议(protocol)的情况下,NAT 遍历是如何工作的。

java - ttorrent 库 HttpResponseMessage 错误

ios - 将 WKInterfaceController 滚动回顶部

ios - UITapGestureRecognizer initWithTarget :action: method to take arguments?

ios - 当 AlertController 出现时,UICollectionViewFlowLayout 错误

iphone - 为什么addSubview会异步加载 View

xcode - 从WebView获取当前URL和标题

c++ - Abort() 已被调用 - Connect Function multithreads Cpp