C++ 字節流 CByteBuffer

 
 
CByteBuffer使用
static void Main()
{
    BYTE a;
    short b;
    int c;
    CByteBuffer buffer;
    buffer<<a<<b<<c;
}

 

 

class
CByteBuffer { public: BYTE* m_lpBuf; int nCurrentIndex; int nCapacity; int nLen; CByteBuffer() { Init(128); } CByteBuffer(int nCapacityIn) { Init(nCapacityIn); } ~CByteBuffer() { delete [] m_lpBuf; m_lpBuf=NULL; } void GetMoreCapacity() { BYTE *pBytesMore=new BYTE[nCapacity*2]; //兩倍 memcpy(pBytesMore,m_lpBuf,nCapacity*sizeof(BYTE)); memset(pBytesMore+nCapacity,0x00,nCapacity*sizeof(BYTE)); delete [] m_lpBuf; m_lpBuf=pBytesMore; nCapacity*=2; } template<typename T> CByteBuffer& operator <<(T dw) { int nSizeNew=nCurrentIndex + sizeof(T); while(nSizeNew>nCapacity) { GetMoreCapacity(); //緩衝區空間不夠 } *(T*)(&m_lpBuf[nCurrentIndex])=dw; //添入緩衝區 nCurrentIndex += sizeof(T); //移動當前索引 nLen+=sizeof(T); return *this; } private: void Init(int nCapatityIn) { nCapacity=nCapatityIn; m_lpBuf=new BYTE[nCapatityIn]; memset(m_lpBuf,0x00,nCapacity); nCurrentIndex=0; nLen=0; } };
相關文章
相關標籤/搜索