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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 ?yp0$r/  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 ;+ G9-  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 B s,as  
象当作char数组来处理。 J/t!- !  
template<class Container> "IG+V:{ou  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, nX._EC  
void, void> Z v4<b  
{ _9NVE|c;  
public: R uLvG+  
explicit bit_iterator(Container& c) : m_container(&c) J='W+=N  
{ 0N{+y}/G  
m_size = 8*sizeof(Container); Ib1e#M3  
m_index = 0; h~w4, T  
} W (`c  
explicit bit_iterator() : m_container(0) azo0{`S?  
{ *zy'#`>  
m_size = 8*sizeof(Container); RlsVC_H\  
m_index = m_size; 1kmQX+f  
} O% -h&C3  
bool operator* () Ziz=]D_  
{ y? "@v.  
char mask = 1; (S oo<.9~  
char* pc = (char*)m_container; H0a -(  
int i   = (m_size-m_index-1)/8; =Y9\DeIZ  
int off   = (m_size-m_index-1)%8; ANMYX18M  
mask <<=off; 0KAj]5nvb  
return pc & mask; ^mg*;8e Ga  
} [T`}yb@  
bit_iterator<Container>& operator++() 3sFeP &  
{ nLy#|C  
m_index++; "!H@k%eAM|  
return *this; 5 lTD]d  
} Q.k :\m*h  
bit_iterator<Container>& operator++(int) /s c.C  
{ %9o+zg? RJ  
m_index++; M^6$ MMx  
return *this; 1zjaR4Tf  
} Ax!Gu$K2o  
bool operator==(bit_iterator<Container>& bitIt) kZVm1W1  
{ iq6a|XGi  
return m_index == bitIt.m_index; xMI+5b8  
} 0Q~@F3N-\>  
bool operator!=(bit_iterator<Container>& bitIt) O"*`'D|hK  
{ t};~H\:  
return !(*this == bitIt); TJaeQqob  
} sS!w}o2X  
protected: $ [7 Vgs  
Container* m_container; k=/eM$":  
private: @u) 'yS  
int m_size; B8m_'!;;  
int m_index; H{V)g  
}; nxaT.uFd1  
h1+ hds+  
用该迭代器可以将任意类型对象以二进制格式输出: (ZP87Gz  
double a = 10; ->E=&X  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

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