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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 w}wABO  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 '<}N`PS#N  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 x4$#x70?  
象当作char数组来处理。 Y[=X b  
template<class Container> `QpkD8  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, T$p!I RPt  
void, void> 3#O R fr(  
{ *] H8X=[x  
public: N:"S/G>r ;  
explicit bit_iterator(Container& c) : m_container(&c) =UGyZV:z5  
{ S}@J4}*u["  
m_size = 8*sizeof(Container); kx6AMx!nX  
m_index = 0; ZCP r`H  
} Bu[sSoA  
explicit bit_iterator() : m_container(0) }XJA#@  
{ M0+xl+c+  
m_size = 8*sizeof(Container); 4f)B@A-  
m_index = m_size; g4Y1*`}2f  
} b4 Y<  
bool operator* () 4=BIYC"Lu  
{ %rU8^'Gu  
char mask = 1; ;\[n{<   
char* pc = (char*)m_container; (gdi 2  
int i   = (m_size-m_index-1)/8; Rm i4ZPb.  
int off   = (m_size-m_index-1)%8; .uo9VL<  
mask <<=off; z|p C*1A\  
return pc & mask; d`}t!]Gg  
} _#9F@SCA  
bit_iterator<Container>& operator++() u,E_Ezq  
{ ,~ z*V;y)  
m_index++; w"A.*8Iu  
return *this; M>eMDCB\  
} b3'U }0Ug  
bit_iterator<Container>& operator++(int) ,>YW7+kY  
{ oGtz*AP%  
m_index++; ~Ox !7Lp  
return *this; /6K9? /  
} 2=\} 0  
bool operator==(bit_iterator<Container>& bitIt) RgB5'$x}  
{ (hB+DPi  
return m_index == bitIt.m_index; G+?Z=A:T8  
} <D_UF1Pk  
bool operator!=(bit_iterator<Container>& bitIt) ]~YY#I":  
{ , QB]y|:  
return !(*this == bitIt); Fv| )[>z0  
} 0bl?dOV{  
protected: ? Zhnb0/  
Container* m_container; Gr),o6}p  
private: S.4gfY  
int m_size; DlMT<ld  
int m_index; H ~VeY\:w  
}; bS1?I@  
)#(6J  
用该迭代器可以将任意类型对象以二进制格式输出: >}"9heF  
double a = 10; 4qsP/`8  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

您目前还是游客,请 登录注册
如果您在写长篇帖子又不马上发表,建议存为草稿
认证码:
验证问题:
3+5=?,请输入中文答案:八 正确答案:八