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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 `NCwK6/i  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 G,?hp>lj  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 U{7w#>V .  
象当作char数组来处理。 ]RPs|R?  
template<class Container> 10)jsA  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, Bp_$.!Qy  
void, void> tjIl-IQ  
{ :o|\"3  
public: \w/yF4,3<w  
explicit bit_iterator(Container& c) : m_container(&c) `IP/d  
{ +ln9c  
m_size = 8*sizeof(Container); +]*zlE\N`  
m_index = 0; ozmrw\_}[  
} 13=A  
explicit bit_iterator() : m_container(0) [$qyF|/K`n  
{ )2Wi `ZT  
m_size = 8*sizeof(Container); 7|{}\w(I  
m_index = m_size; ;nep5!s;<  
} "fG8?)d;  
bool operator* () n!YKz"$  
{ !TAlB kj  
char mask = 1; f%SZg!+t  
char* pc = (char*)m_container; DK$X2B"cV  
int i   = (m_size-m_index-1)/8; JLnH&(O  
int off   = (m_size-m_index-1)%8; {K+i cTL3  
mask <<=off; >"|B9Woc  
return pc & mask; %SX|o-B~.o  
} \n$u)Xj~6^  
bit_iterator<Container>& operator++() h]Wr [v  
{ `b Fff %_  
m_index++; I KqQ>Z-q~  
return *this; dCE0$3'5  
} < vL,*.zd  
bit_iterator<Container>& operator++(int) 1;C+$  
{ 1,6}_MA  
m_index++; 9KDEM gCW  
return *this; Lx\ 8Z=  
} QN #U)wn:  
bool operator==(bit_iterator<Container>& bitIt) J3e96t~u  
{ N*"p|yhd]  
return m_index == bitIt.m_index; '10oK {m$  
} j}%ja_9S  
bool operator!=(bit_iterator<Container>& bitIt) wb]%m1H`:  
{ d6'{rje(  
return !(*this == bitIt); c9HrMgW  
} *AG#316  
protected: <oR a3Gi(%  
Container* m_container; k[bD\'  
private: &,}j #3<  
int m_size; JW{rA6?   
int m_index; q)Lu_6 mg  
}; 3Ndq>  
 8cU}I4|  
用该迭代器可以将任意类型对象以二进制格式输出: y+X2Pl  
double a = 10; M.x=<:upp  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

您目前还是游客,请 登录注册
欢迎提供真实交流,考虑发帖者的感受
认证码:
验证问题:
10+5=?,请输入中文答案:十五