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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 `@nl  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 #B4%|v;`E?  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 EK4d_L]I  
象当作char数组来处理。 :Nz9xD$S5  
template<class Container> \[y`'OD~  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, gLOEh6  
void, void> oH_;4QU4y  
{ rx]  @A  
public: .ev?"!Vpp9  
explicit bit_iterator(Container& c) : m_container(&c) E{|W(z,  
{ ,^C--tgZJg  
m_size = 8*sizeof(Container); EM[WK+9>I{  
m_index = 0; u:=7l  
} Ymg|4 %O@  
explicit bit_iterator() : m_container(0) #3gp6*R  
{ NuQdSj_>  
m_size = 8*sizeof(Container);  iKT[=c  
m_index = m_size; h2XfC. f  
} y!_C/!d  
bool operator* () ]7RD"}  
{ >Z'NXha  
char mask = 1; ]x(!&y:h  
char* pc = (char*)m_container; V=o t-1,j7  
int i   = (m_size-m_index-1)/8; a6uJYhS~  
int off   = (m_size-m_index-1)%8; eS~LF.^Jw  
mask <<=off; UWd=!h^dt  
return pc & mask; $w`=z<2yo1  
} Y2~nBb  
bit_iterator<Container>& operator++() 67Th;h*sh  
{ toBHkiuD  
m_index++; (2$p{Uf  
return *this; |R/%D%_g  
} -#N.X_F  
bit_iterator<Container>& operator++(int) +l<5#pazx  
{ |xdsl,  
m_index++; /7Cc#P6  
return *this; ]QlwR'&j/n  
} woGAf)vV#  
bool operator==(bit_iterator<Container>& bitIt) Y,^@P  
{ 7%x[q}  
return m_index == bitIt.m_index; :LW4E9O=H  
} :&V h?  
bool operator!=(bit_iterator<Container>& bitIt) 1SCR.@ k<  
{ 4R1<nZ"e~  
return !(*this == bitIt); 0dE@c./R i  
} RAgg:3^  
protected: #W4dkCd(pF  
Container* m_container; F%@aB<Nu  
private: 'h|DO/X~L  
int m_size; 3q\,$*D.  
int m_index; o$jLzE"  
}; dMv=gdY  
:V RNs  
用该迭代器可以将任意类型对象以二进制格式输出: !Prg_6 `  
double a = 10; R{<kW9!  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

您目前还是游客,请 登录注册
如果您提交过一次失败了,可以用”恢复数据”来恢复帖子内容
认证码:
验证问题:
10+5=?,请输入中文答案:十五