我正在尝试使用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);..which检索数据,但它后面似乎有额外的unicode垃圾:
File name: ubuntu-8.10-desktop-i386.iso)我也尝试过(from here)..
NSString *secondtry = [NSString stringWithCharacters:[name bytes] length:[name length] / sizeof(unichar)];..but这似乎返回了一堆随机字符:
扵湵畴㠭ㄮⴰ敤歳潴⵰㍩㘸椮潳第一种方法(如苹果文档中提到的)正确地返回了大部分数据,还有一些额外的字节,这让我认为这可能是BEncoding库中的错误。但我对ObjC缺乏了解,这更有可能是我的错。
发布于 2009-02-17 00:07:12
NSData *torrent = BEncoding objectFromEncodedData:原始数据;
当我对torrent执行NSLog操作时,会得到以下内容:
{⋮}
那么,这应该是一个NSDictionary,而不是一个NSData。
unsigned char aBuffer[名称长度];[name getBytes:a缓冲区长度:名称长度];NSLog(@“文件名:%s",aBuffer);
..which检索数据,但它后面似乎有额外的unicode垃圾:
文件名: ubuntu-8.10-desktop-i386.iso)
不,它只是很好地检索了文件名;只是打印错误而已。%s接受一个以null结尾的C字符串;数据对象的字节不是以null结尾的(它们只是字节,不一定是任何编码中的字符,0是一个完全有效的字节)。您必须再分配一个字符,并将数组中的最后一个字符设置为0:
size_t length = [name length] + 1;
unsigned char aBuffer[length];
[name getBytes:aBuffer length:length];
aBuffer[length - 1] = 0;
NSLog(@"File name: %s", aBuffer);但是空终止NSData对象中的数据是错误的(除非您确实需要一个C字符串)。我马上就会找到正确的方法。
我也试过…。。
NSString *secondtry = [NSString字符串字符:名称字节长度:名称长度/大小(Unichar)];
..but这似乎返回随机的中文字符:
扵湵畴㠭ㄮⴰ敤歳潴⵰㍩㘸椮潳
这是因为您的字节是UTF-8,它(通常)在一个字节中编码一个字符。
unichar是并且stringWithCharacters:length:接受UTF-16。在这种编码中,一个字符(通常)是两个字节。(因此除以sizeof(unichar):它将字节数除以2,得到字符数。)
因此,您说“这是一些UTF-16数据”,它从每两个字节中生成字符;每对字节应该是两个字符,而不是一个字符,所以您得到的是垃圾(原来大部分是CJK表意文字)。
You answered your own question非常好,除了stringWithUTF8String:对于UTF-8编码的字符串比stringWithCString:encoding:更简单。
但是,当您有足够的长度时(就像使用NSData时一样),使用initWithBytes:length:encoding:就更容易了,也更合适了。它更简单,因为它不需要以null结尾的数据;它只使用您已有的长度。(不要忘记释放或自动释放它。)
发布于 2009-03-02 23:39:24
我认为这是应该再次强调的重要一点。事实证明,
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];不同于,
NSString *content = [[NSString alloc] initWithBytes:[responseData bytes]
length:[responseData length] encoding: NSUTF8StringEncoding];在上述两种情况下,如果字节字符串没有正确终止,第一个示例中的content将为NULL。
发布于 2011-02-10 09:24:17
怎么样
NSString *content = [[[NSString alloc] initWithData:myData
encoding:NSUTF8StringEncoding] autorelease];https://stackoverflow.com/questions/550405
复制相似问题