Bencode是BitTorrent用在传输数据结构的编码方式。
Bencode(发音为 Bee-Encode)这种编码方式支持四种数据型态:
• 字元串
• 整数
• 串列
• 字典表
Bencode 最常被用在.torrent文档中,文件里的元数据都是 Bencode 过的字典表。其也被用在tracker返回响应时使用。
虽然比用纯二进制编码效率低,但由于结构简单而且不受字节存储顺序影响(所有数字以十进制编码)——这对于跨平台性非常重要。而且具有较好的灵活性,即使存在故障的字典键,只要将其忽略并更换新的就能兼容补充。
使用GEBEncoding完成Bencode
GEBEncoding:An Objective-C BEncoding Library
屏幕快照 2018-06-07 下午4.46.50.png代码结构:
屏幕快照 2018-06-07 下午4.56.45.pngGEBEncoding使用方法:
引入pod库
这个pod库是我根据上面的代码,建立的pod库。方便iOS项目集成。
pod 'GEBEncoding'
编码encode
// +(NSData *)encodeDataFromObject:(id)object
//
// This method to returns an NSData object that contains the bencoded
// representation of the object that you send. You can send complex structures
// such as an NSDictionary that contains NSArrays, NSNumbers and NSStrings, and
// the encoder will correctly serialise the data in the expected way.
//
// Supports NSData, NSString, NSNumber, NSArray and NSDictionary objects.
//
// NSStrings are encoded as NSData objects as there is no way to differentiate
// between the two when decoding.
//
// NSNumbers are encoded and decoded with their longLongValue.
//
// NSDictionary keys must be NSStrings.
+(NSData *)encodedDataFromObject:(id)object;
反编码
// +(id)objectFromEncodedData:(NSData *)sourceData;
//
// This method returns an NSObject of the type that is serialised in the bencoded
// sourceData.
//
// Bad data should not cause any problems, however if it is unable to deserialise
// anything from the source, it may return a nil, which you need to check for.
+(id)objectFromEncodedData:(NSData *)sourceData;
+(id)objectFromEncodedData:(NSData *)sourceData withTypeAdvisor:(GEBEncodedTypeAdvisor)typeAdvisor;
使用效果:
#import <GEBEncoding.h>
NSDictionary * dict = @{@"inputs.sourceType":@"faceID",@"inputs.data":@"qwer"};
NSData * data = [GEBEncoding encodedDataFromObject:dict];
$ po data
"d11:inputs.data4:qwer17:inputs.sourceType6:faceIDe"
网友评论