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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 $F$R4?_  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 pC Is+1O/  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 `;GGuJb \  
象当作char数组来处理。 LZ dNG\-  
template<class Container> hvZR4|k>  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, I"?&X4%e  
void, void> Qn&^.e9I  
{ 6;V 1PK>9  
public: ;g9:0,xT4  
explicit bit_iterator(Container& c) : m_container(&c) ZJM^P'r.1c  
{ %*}f<k{6  
m_size = 8*sizeof(Container); aBLb i  
m_index = 0; 2 -8:qmP(  
} 'mR+W{r  
explicit bit_iterator() : m_container(0) IV*$U7~  
{ )C6 7qY  
m_size = 8*sizeof(Container); ^<+heX  
m_index = m_size; !qv;F?2 <g  
}  p$v +L  
bool operator* () y5h[^K3  
{ f/m6q8!L{  
char mask = 1; >*CK@"o  
char* pc = (char*)m_container; -2d&Aq4m)  
int i   = (m_size-m_index-1)/8; OUMr}~/  
int off   = (m_size-m_index-1)%8; "V2$g  
mask <<=off; essW,2,rjC  
return pc & mask; [GM<Wt0  
} )CQ}LbXZy  
bit_iterator<Container>& operator++() ZeV)/g,w  
{ L,L7WObA  
m_index++; "KwKO8f  
return *this; t,nB`g?  
} T667&@  
bit_iterator<Container>& operator++(int) B[50{;X  
{ b*fflJ  
m_index++; $S{j}74[  
return *this; g.s oN qt=  
} &.B6P|N'  
bool operator==(bit_iterator<Container>& bitIt) p60D{UzU  
{ X.<R['U&\  
return m_index == bitIt.m_index; Bs}>#I  
} iSHl_/I<  
bool operator!=(bit_iterator<Container>& bitIt) Xi.?9J`@  
{ 37Y]sJrs$  
return !(*this == bitIt); gZv <_0N  
} =oJiNM5_u  
protected: t;3.;  
Container* m_container; AF6'JxG7  
private: (%}C  
int m_size; P+h&tXZn8  
int m_index; ZbUf|#GTB  
}; w3D_ c~  
I "4B1g  
用该迭代器可以将任意类型对象以二进制格式输出: g=Di2j{A  
double a = 10; $}fA;BP  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

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