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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 =E!Y f#p+q  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 (`#z@,1  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 3'i(wI~<[  
象当作char数组来处理。 aqK+ u.H  
template<class Container> \JR^uJ{Y  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, -(lP8Y~gFY  
void, void> b+arnKo1fk  
{ O x`K7$)  
public: 6;s[dw5T  
explicit bit_iterator(Container& c) : m_container(&c) W?kJ+1"(  
{ CSW+UaE  
m_size = 8*sizeof(Container); NMhpKno  
m_index = 0; nq>F_h  
} u&TXN;I,p  
explicit bit_iterator() : m_container(0) nnT#S  
{ XHJ` C\xR  
m_size = 8*sizeof(Container); a-F I`Dv  
m_index = m_size; 5#X R1#`  
} /uR/,R++  
bool operator* () biw . ~  
{ ,=G]tnsv^  
char mask = 1; [\h?mlG?  
char* pc = (char*)m_container; 0&CXR=U5  
int i   = (m_size-m_index-1)/8; HIE8@Rv/3  
int off   = (m_size-m_index-1)%8; Z1 ($9hE>  
mask <<=off; z'1%%.r;FM  
return pc & mask;  CDuA2e  
} ]i0=3H2  
bit_iterator<Container>& operator++() W4k$m 2  
{ +zLw%WD[l  
m_index++; -z-yk~F  
return *this; /|}yf/^9X  
} ),Yk53G6c  
bit_iterator<Container>& operator++(int) kkb+qo  
{ @Y.r ,q  
m_index++;  -K8F$\W  
return *this; E11C@%  
} GRofOJ  
bool operator==(bit_iterator<Container>& bitIt) Rmn{Vui9\  
{ i_r708ep6  
return m_index == bitIt.m_index; { 29aNm  
} IDos4nM27]  
bool operator!=(bit_iterator<Container>& bitIt) =v<A&4  
{ Ck %if  
return !(*this == bitIt); ;Sg.E 8  
} .b<W*4{j0H  
protected: A:Gd F-;[  
Container* m_container; 8 qw{e`c  
private: c[ 0`8s!  
int m_size; 4J(-~  
int m_index; y`7<c5zD  
}; M&faa7  
srO>l ;Vf/  
用该迭代器可以将任意类型对象以二进制格式输出: 6H  U*,  
double a = 10; 6~W@$SP,F  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

您目前还是游客,请 登录注册
如果您在写长篇帖子又不马上发表,建议存为草稿
认证码:
验证问题:
10+5=?,请输入中文答案:十五