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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 qgs:9V xF  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 ]DUmp6  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 '=H3Y_{oO  
象当作char数组来处理。 4j}.=u*X7  
template<class Container> G%junS'zt  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, l1.eAs5U  
void, void> ?pdN!zOeL  
{ SBaTbY0  
public: E9w"?_A)  
explicit bit_iterator(Container& c) : m_container(&c) _aU :[v*!  
{ Vp1Q^`a{G  
m_size = 8*sizeof(Container); J vl-=~  
m_index = 0; 4}Y? :R  
} RT2&^9-  
explicit bit_iterator() : m_container(0) cJ>^@pd{  
{ j*FpQiBoT  
m_size = 8*sizeof(Container); Ax 4R$P.]u  
m_index = m_size; sZwa#CQKq  
} ?k=)T]-}  
bool operator* () "u'dd3!  
{ lmIphOUoIw  
char mask = 1; np\*r|U  
char* pc = (char*)m_container; 1wE`kbC<  
int i   = (m_size-m_index-1)/8;  wH\ K'/  
int off   = (m_size-m_index-1)%8; M=fhRCUB  
mask <<=off; BwYR"  
return pc & mask; =y^ g*9}_  
} "HLh3L~  
bit_iterator<Container>& operator++() P  V9q=  
{ x}f)P  
m_index++; <J]N E|:  
return *this; iA4VT,  
} {M23a _t\  
bit_iterator<Container>& operator++(int) - v=ndJ.  
{ SbobXTbG  
m_index++; 6|Crc$4l  
return *this; :2lM7|@/  
} AY]rQ:I  
bool operator==(bit_iterator<Container>& bitIt) T2to!*T  
{ ?U,XyxN  
return m_index == bitIt.m_index; orEb+  
} G&yF9s)Lvs  
bool operator!=(bit_iterator<Container>& bitIt) [3] h(D  
{ G[ q<P  
return !(*this == bitIt); 6f J5Y iQ  
} _Ry  
protected: V'AZs;  
Container* m_container; <2\Q Y  
private: s="cg0PD  
int m_size;  P!/:yWd  
int m_index; n* z;%'0  
}; 'fIG$tr9X  
<$ %Y#I'zX  
用该迭代器可以将任意类型对象以二进制格式输出: I -XkxDw  
double a = 10; 6w0r)  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

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