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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 . mO8 ~Z  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。  y_[VhZ%  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 ={cM6F}a@  
象当作char数组来处理。 CZ] Dm4  
template<class Container> mB0`>?#i  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, R&t2   
void, void> "dv\ 9O  
{ MwQtf(_  
public: NMw5ixl  
explicit bit_iterator(Container& c) : m_container(&c) @eBo7#Zr  
{ \M.?*p  
m_size = 8*sizeof(Container); 9HN&M*}  
m_index = 0; :tFc Pc'  
} yO8@.-jb  
explicit bit_iterator() : m_container(0) e^\(bp+83  
{ ]6v7iuvI  
m_size = 8*sizeof(Container); BR@gJ(2  
m_index = m_size; LC=M{\  
} H&*&n}vh5y  
bool operator* () I&15[:b=-  
{ ,ynN801\m  
char mask = 1; lgVT~v{U`n  
char* pc = (char*)m_container; }Tm+gJA  
int i   = (m_size-m_index-1)/8; fuHNsrNlm  
int off   = (m_size-m_index-1)%8; #+6j-^<_6  
mask <<=off; 7W},5c  
return pc & mask; 2<0".5+I  
} <<qzZ+u  
bit_iterator<Container>& operator++() [8tpU&J  
{ >(n /  
m_index++; ho^c#>81  
return *this; `r=^{Y  
} 4?(=?0/[  
bit_iterator<Container>& operator++(int) (K6vXq.;\\  
{ A6_ER&9$>N  
m_index++; |I"&Z+m  
return *this; J Z@sk2  
} UjunIKX+  
bool operator==(bit_iterator<Container>& bitIt) M^l%*QF[,q  
{ c+Z dfdR  
return m_index == bitIt.m_index; _z]v;Q  
}  wDiq~!  
bool operator!=(bit_iterator<Container>& bitIt) 0#yH<h$   
{ SI6?b1;-:F  
return !(*this == bitIt); `{w|2 [C3  
} c3fi<?0&|  
protected: 2HE<WI^#h  
Container* m_container; 8KR17i1  
private: 7Y.yl F:  
int m_size; T[[E)f1[  
int m_index; g] IPNW^n  
}; i/8OC  
p|0SA=?k"  
用该迭代器可以将任意类型对象以二进制格式输出: >3p8o@:  
double a = 10; *hFJI9G  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

您目前还是游客,请 登录注册
批量上传需要先选择文件,再选择上传
认证码:
验证问题:
3+5=?,请输入中文答案:八 正确答案:八