首页 > 其他 > 详细

我的开源项目:一种TLV编解码器的实现

时间:2015-12-04 06:35:26      阅读:868      评论:0      收藏:0      [点我收藏+]

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


维基百科的定义如下:https://en.wikipedia.org/wiki/Type-length-value


一个TLV对象示例如下:


技术分享 

 

多个TLV对象可以连接起来,组成一个大的buffer,TLV对象内部也可以嵌套另一个TLV对象:


技术分享


我希望能提供一套API接口(C/C++/Java/其他语言),可以方便地完成TLV格式的编码和解码,项目地址如下所示:


https://github.com/Jhuster/TLV


其中,C++版本已经实现,介绍如下:


1. TLV编码的接口


//Put one TLV box
bool PutCharValue(int type,const char &value);
bool PutShortValue(int type,const short &value);
bool PutIntValue(int type,const int &value);
bool PutLongValue(int type,const long &value);
bool PutLongLongValue(int type,const long long &value);
bool PutFloatValue(int type,const float &value);
bool PutDoubleValue(int type,const double &value);
bool PutStringValue(int type,const char *value);
bool PutBytesValue(int type,const unsigned char *value,int length);
bool PutObjectValue(int type,const TlvObject& value);
bool PutValue(int type,const void *value,int length);     

//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 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 GetBytesValue(int type,unsigned char *value,int &length) const;
bool GetBytesValuePtr(int type,unsigned char **value,int &length) const;
bool GetObjectValue(int type,TlvObject& value) const;
bool GetValue(int type,const void **value,int& length) const;


3. 具体用法


请参考代码目录下的 Test.cpp,有任何疑问欢迎来信lujun.hust@gmail.com交流,提交issue,也欢迎为本项目贡献代码,谢谢。


欢迎大家关注我的新浪微博 @卢_俊 获取最新的文章和资讯。



本文出自 “Jhuster的专栏” 博客,请务必保留此出处http://ticktick.blog.51cto.com/823160/1719378

我的开源项目:一种TLV编解码器的实现

原文:http://ticktick.blog.51cto.com/823160/1719378

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!