移动专线

TLV,全称是“type-length-value”,与“XML”、“Json”这些“字节流”格式不同,它是一种“二机制流”格式,不易阅读,但更省带宽,更容易压缩,常用于通信协议中的变长部分。

一个TLV对象示例如下:

wKioL1ZgS5TjVAGNAAAR9aYejqE708.png

多个TLV对象可以连接起来,组成一个大的buffer:

wKioL1ZgS_iTTHB-AAAUS1zKw08795.png

一个TLV对象内部也可以嵌套另一个TLV对象:

扫描二维码关注公众号,回复: 11480428 查看本文章

其中,C++版本已经实现(更新:C/Java/Android版本也均已实现),介绍如下:

1. TLV编码的接口

//put one TLV box
bool PutBoolValue(int type,bool value);
bool PutCharValue(int type,char value);
bool PutShortValue(int type,short value);
bool PutIntValue(int type,int value);
bool PutLongValue(int type,long value);
bool PutLongLongValue(int type,long long value);
bool PutFloatValue(int type,float value);
bool PutDoubleValue(int type,double value);
bool PutStringValue(int type,char *value);
bool PutStringValue(int type,const std::string &value);
bool PutBytesValue(int type,unsigned char *value,int length);
bool PutObjectValue(int type,const TlvBox& value);          

//do encode
bool Serialize(); 

//access encoded buffer and length
unsigned char * GetSerializedBuffer() const;
int GetSerializedBytes() const;

2. TLV解码的接口

//do decode
bool Parse(const unsigned char *buffer,int buffersize); 

//get one TLV box
bool GetBoolValue(int type,bool &value) const;
bool GetCharValue(int type,char &value) const;
bool GetShortValue(int type,short &value) const;
bool GetIntValue(int type,int &value) const;
bool GetLongValue(int type,long &value) const;
bool GetLongLongValue(int type,long long &value) const;
bool GetFloatValue(int type,float &value) const;
bool GetDoubleValue(int type,double &value) const;
bool GetStringValue(int type,char *value,int &length) const;
bool GetStringValue(int type,std::string &value) const;
bool GetBytesValue(int type,unsigned char *value,int &length) const;
bool GetBytesValuePtr(int type,unsigned char **value,int &length) const;
bool GetObjectValue(int type,TlvBox& value) const;

猜你喜欢

转载自blog.csdn.net/blabc2012/article/details/107704624