社区应用 最新帖子 精华区 社区服务 会员列表 统计排行 社区论坛任务 迷你宠物
  • 2789阅读
  • 0回复

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 P,,@&* :  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 &Uzg&eB  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 e\\ I,  
象当作char数组来处理。 /H}83 C  
template<class Container> ?:UDK?  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, p`Ax)L\f  
void, void> `2GHB@S"k  
{ nL\BB&  
public: [^aow-4z  
explicit bit_iterator(Container& c) : m_container(&c) y%43w4  
{ ,;UVQwY  
m_size = 8*sizeof(Container); Qp{{OjD  
m_index = 0; ~~>D=~B0'  
} >YD? pDPb/  
explicit bit_iterator() : m_container(0) d6wsT\S  
{ [0  3Aej  
m_size = 8*sizeof(Container); i/~A7\:8%  
m_index = m_size; x#'# ~EO-G  
}  /I="+  
bool operator* () P.LMu  
{ vX&Nh"0H&  
char mask = 1; EFV'hMjS)  
char* pc = (char*)m_container; ?FD^S~bz-  
int i   = (m_size-m_index-1)/8; {]`O$S  
int off   = (m_size-m_index-1)%8; $dq R]'  
mask <<=off; e3&R3{  
return pc & mask; {5:y,=Y  
} &d=j_9   
bit_iterator<Container>& operator++() YMC*<wXN  
{ |]^OX$d  
m_index++; F?TAyD*  
return *this; 5_{C \S`T  
} wQDKv'zU1  
bit_iterator<Container>& operator++(int) 1)H+iN|im/  
{ {i3]3V"Xp  
m_index++; LY/K ,6^a  
return *this; /z`LB  
} <!R~G-D#_T  
bool operator==(bit_iterator<Container>& bitIt) 0zetOlFbO  
{ $GEY*uIOa  
return m_index == bitIt.m_index; GoZr[=d  
} NEJxd%-  
bool operator!=(bit_iterator<Container>& bitIt) zaa>]~g.  
{ Ee d2`~  
return !(*this == bitIt); ux'!1mN  
} r:<UV^; 9l  
protected: X& pK#=  
Container* m_container; E\5t&jZr  
private: !Mceg  
int m_size; |I6\_K.=L  
int m_index; WM~@/J  
}; 2{% U\^-  
dk# LAm0<  
用该迭代器可以将任意类型对象以二进制格式输出: NO8)XJ3s  
double a = 10; #1+1q{=Z<  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

您目前还是游客,请 登录注册
欢迎提供真实交流,考虑发帖者的感受
认证码:
验证问题:
3+5=?,请输入中文答案:八 正确答案:八