iOS的Bencode編解碼應(yīng)用(pod 'GEBEncoding')

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

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"
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容