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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 39i9wrP  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 /+]s.V.  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 s +s" MI  
象当作char数组来处理。 C.Uju`3  
template<class Container> pB:$lS  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, b1#dz]  
void, void> e [h8}F  
{ #Pk$L+C  
public: =EP13J  
explicit bit_iterator(Container& c) : m_container(&c) K=::)/{P  
{ zYER  
m_size = 8*sizeof(Container); lSwcL  
m_index = 0; _fk#<  
} &53]sFZ  
explicit bit_iterator() : m_container(0) 3VO2,PCZ  
{ W_|0y4QOo  
m_size = 8*sizeof(Container); 0% L l  
m_index = m_size; .Pndx%X9s  
} Jju#iwb  
bool operator* () `fNpY#QsN  
{ xw5d|20b  
char mask = 1; A7_4 .VH  
char* pc = (char*)m_container; 9A'Y4Kg<C  
int i   = (m_size-m_index-1)/8; ?%tMohL  
int off   = (m_size-m_index-1)%8; C4$:mJ>y  
mask <<=off; Sl2iz?   
return pc & mask; 1T&Rc4$Sn7  
} jKIxdY:U  
bit_iterator<Container>& operator++() b}^S.;vNj  
{ LpbsYl  
m_index++; @$^bMIj@W  
return *this; DTRJ/ @t  
} o G*5f  
bit_iterator<Container>& operator++(int) G3P &{.v  
{ /6uT6G+(z}  
m_index++; LkruL_E>  
return *this; &)wiKh"$  
} }Db[ 4  
bool operator==(bit_iterator<Container>& bitIt) 3g'S\ G@  
{ s8"8y`u  
return m_index == bitIt.m_index; {P%9  
} yF}OfK?0f  
bool operator!=(bit_iterator<Container>& bitIt) ))kF<A_MK  
{ z G }?  
return !(*this == bitIt); ;ea] $9  
} z;f2*F  
protected: pIV-kI:w  
Container* m_container; olB)p$aH#  
private: 1@48BN8cm'  
int m_size; )> ,wj  
int m_index; d_UN0YT<  
}; B(a-k?  
ia&AW  
用该迭代器可以将任意类型对象以二进制格式输出: (_kp{0r#  
double a = 10; e~%  ;K4  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

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