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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 >WG$!o+R  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 ~vG~Z*F  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 S1zV.]  
象当作char数组来处理。 !%]]lxi  
template<class Container> MNkysB(  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, 2}+V3/  
void, void> m<r.sq&;  
{ oDA1#-  
public: RM QlciG  
explicit bit_iterator(Container& c) : m_container(&c) [bE9Y;  
{ >|H=25N>;  
m_size = 8*sizeof(Container); zn@tLLX  
m_index = 0; F5&4x"c  
} L +-B,466  
explicit bit_iterator() : m_container(0) { 5h6nYu  
{ Zj!S('hSY  
m_size = 8*sizeof(Container); &eyFApM[Z  
m_index = m_size; K*p^Gs,  
} mtmtOG_/=  
bool operator* () =3""D{l  
{ #^#N%_8  
char mask = 1; eEupqOF*:W  
char* pc = (char*)m_container; g9p#v$V  
int i   = (m_size-m_index-1)/8; \tU91 VIj  
int off   = (m_size-m_index-1)%8; O:#t> ;  
mask <<=off; hA)3Ah*  
return pc & mask; Xg#Dbf4  
} e6#^4Y/+`  
bit_iterator<Container>& operator++() .2Gn)dZU  
{ d\xh>o  
m_index++; -KbT[]  
return *this; Cv~t~  
} #%B1, .A  
bit_iterator<Container>& operator++(int) JFl@{6c  
{ h dPK eqg7  
m_index++; O*!+D-  
return *this; Q]7r?nEEhW  
} A5B 5pJ  
bool operator==(bit_iterator<Container>& bitIt) M9 _h0  
{  X1y1  
return m_index == bitIt.m_index; W<v?D6dFq  
} 0M-Zp[w\-  
bool operator!=(bit_iterator<Container>& bitIt) ; #e-pkV  
{ c :hOQZ  
return !(*this == bitIt); 3fn6W)v?  
} lOcvRF  
protected:  /dBQ*f5  
Container* m_container; Y KeOH  
private: i%v^Zg&FU  
int m_size; R&=Y7MfZ  
int m_index; 44($a9oa2  
}; N2xgyKy~  
7@|(z:uw  
用该迭代器可以将任意类型对象以二进制格式输出: 6^}GXfJAc  
double a = 10; e,|"9OK  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

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