a byte string for store low level data type css
在基于TCP/UDP 或者串口通讯等底层的通讯过程当中。涉及到大量的字符串操做:存储,拷贝, 传參 等。java
xbytestring 类时面向底层通讯,专门针对 unsigned char 字符串操做的而开发的。 相对于使用 字符指针的开发方式, xbytestring 具有 调用方便, 安全的特性,很是好的攻克了 字符串操做过程当中遇到的诸多缺陷,于此同一时候 xbytestring 可以很是好的兼容 ST::string 。unsigned char ,char 数据类型,方便开发人员更加在各个数据类型之间转化。 c++
在低层次的网络通讯过程当中。所有的数据都是经过 ascii 码的形式接受和传输。使用char,或者unsigned char的数据类型 进行数据的存储或者传递 对于上层的开发时是很是不方便。git
由于期间涉及到大量的动态内存建立 和删除,指针传递。拷贝,内存溢出则是这其中最easy引起的问题,这是另无数开发头疼不已的问题,尽管很是多状况下可以用智能指针解决问题。但是对于字符的操做却不老是那么的安全和友好。 github
- C 语言的特性 : 为了高效而牺牲了代码的安全
- 高级的语言特性 : 牺牲代码的效率来换取 代码安全和开发效率
略微有开发经验的读者可能联想到了 STL库提供的 std::string来解决问题. string 可以很是好的作到 字符串数据的存储和 传递, 但是在实际的开发的过程当中,基于UDP /TCP 协议的网络通讯中,涉及到大量的使用0x00
这种字符表明的操做, 而string 天生对0x 00
敏感的特性(默以为结束符),致使string会本身主动丢弃在接受到0x00
字符后的所有的数据.
很是显然,这不是咱们所但愿看到的结果。安全
为了更好的兼容
0x00
。方便的存储和传參的需求。 在开发过程当中急需一 类似于string
的容器。可以很是好的存储网络其中给定长度的 字符串.markdown
通过一番谷歌以后, 仅有的一点发现也只 是 java 平台下的 ByteString ,很是惋惜,这不是给C++ 用的, 考虑再三,为何不重造一个呢? 造轮子但是C++ 的专利啊。 网络
- 操做方便安全,接口友好
- 兼容 string 的接口
- 默认存储 unsigned char
- 高速实现 xbytestring 和 char ,string 数据类型的转化
- 自由拓展字符串长度
- 内存安全
///////////////////////////////////////////////////////////////
/* File name : Xbytestring.h Author : LEO Date : 2015-3-12 Email : lion_117@126.com Description: All Rights Reserved */
///////////////////////////////////////////////////////////////
#pragma once
#include <string>
#include <vector>
using namespace std;
typedef unsigned char u_char;
typedef unsigned int u_int;
class Xbytestring
{
private: // to realize the copy constructor fuction
vector<u_char> list_datastring;
public:
Xbytestring(void);
Xbytestring(u_char *pchar , u_int nlenth);
Xbytestring(string pstring);
Xbytestring(const Xbytestring &obj_string);
u_char & operator[](u_int nindex);
Xbytestring operator+(Xbytestring & obj_a );
~Xbytestring(void);
public:
u_int size();
u_char at( u_int nindex);
bool empty();
void clear();
void c_str( u_char *pchar );
string tostring();
string tosafestring();
void setdata(u_char *pchar , u_int nlenth);
void setdata(string pstr);
void setdata(Xbytestring pobj);
//**********abandon function interface ******//
void Set_data(u_char *pchar , u_int nlenth);
void Set_data(string pstr);
//*******************************************//
void append(u_char *pchar , u_int nlenth);
void append(string pstring);
void append(u_char pchar);
void append(Xbytestring pobj);
void erease(u_int nindex);
private:
bool Copy_deep(u_char * pstr , u_int nlenth);
};
点击此连接下载源代码app