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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 @i$9c)D  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 go@UE2qw  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 'n#;~  
象当作char数组来处理。 *y='0)[BD  
template<class Container> b{b2L.  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, O!\P]W4r$  
void, void> 25::z9i  
{ tl (2=\  
public: KArR.o }  
explicit bit_iterator(Container& c) : m_container(&c) _K_!(]t  
{ QDF1$,s4i  
m_size = 8*sizeof(Container); (UA a  
m_index = 0; C~yfuPr\B  
} 1*Yf[;L  
explicit bit_iterator() : m_container(0) V&eti2 &zO  
{ UMma|9l(i  
m_size = 8*sizeof(Container); Gvb>M=9  
m_index = m_size; wbyY?tH  
} nz3j";d  
bool operator* () ?nn`ud?f  
{ o6 'I%Gs  
char mask = 1; h*Rh:yCR>  
char* pc = (char*)m_container; *}-X '_  
int i   = (m_size-m_index-1)/8; I_6?Q^_uZ  
int off   = (m_size-m_index-1)%8; <_dyUiT$J  
mask <<=off; `kpX}cKK}  
return pc & mask; X2}\i5{  
} hJ (Q^Z  
bit_iterator<Container>& operator++() 1j`-lD  
{ Q&opnvN  
m_index++; lQ<2Vw#Yl  
return *this; +\fr3@Yc  
} =!*e; L  
bit_iterator<Container>& operator++(int) j#f+0  
{ C\ZL*,%}  
m_index++; xdd7OSc0{  
return *this; 0~iC#lHO  
} rr>QG<i;G  
bool operator==(bit_iterator<Container>& bitIt) iKnH6} `?U  
{ r`qMif'  
return m_index == bitIt.m_index; w4Qqo(  
} [2pp)wq  
bool operator!=(bit_iterator<Container>& bitIt) 6iV jAxR  
{ '_lyoVP  
return !(*this == bitIt); L'BDS*  
} 5bYU(]  
protected: : ^F+m QN  
Container* m_container; CC0@RU  
private: AON";&dLq-  
int m_size; HgvgO\`]  
int m_index; 0&mo1 k_U  
}; @zL)R b%P$  
! @{rk p  
用该迭代器可以将任意类型对象以二进制格式输出: 1P. W 34  
double a = 10; ^VK-[Sz&  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

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