Bencode是BitTorrent用在傳輸數(shù)據(jù)結(jié)構(gòu)的編碼方式。
Bencode(發(fā)音為 Bee-Encode)這種編碼方式支持四種數(shù)據(jù)型態(tài):
? 字元串
? 整數(shù)
? 串列
? 字典表
Bencode 最常被用在.torrent文檔中,文件里的元數(shù)據(jù)都是 Bencode 過的字典表。其也被用在tracker返回響應(yīng)時(shí)使用。
雖然比用純二進(jìn)制編碼效率低,但由于結(jié)構(gòu)簡(jiǎn)單而且不受字節(jié)存儲(chǔ)順序影響(所有數(shù)字以十進(jìn)制編碼)——這對(duì)于跨平臺(tái)性非常重要。而且具有較好的靈活性,即使存在故障的字典鍵,只要將其忽略并更換新的就能兼容補(bǔ)充。
使用GEBEncoding完成Bencode
GEBEncoding:An Objective-C BEncoding Library

屏幕快照 2018-06-07 下午4.46.50.png
代碼結(jié)構(gòu):

屏幕快照 2018-06-07 下午4.56.45.png
GEBEncoding使用方法:
引入pod庫
這個(gè)pod庫是我根據(jù)上面的代碼,建立的pod庫。方便iOS項(xiàng)目集成。
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"