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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 >/W  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 `v;9!ReZV  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 U7GgGMw  
象当作char数组来处理。 ep|>z#1  
template<class Container> LU'<EXUbY  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, ~cC =DeX  
void, void> Fog4m=b`g  
{ {, +,:w7  
public: .x6c.Y.S  
explicit bit_iterator(Container& c) : m_container(&c) Y z"B  
{ v2Lx4:dzi  
m_size = 8*sizeof(Container); VTM*=5|c   
m_index = 0; c*fMWtPp  
} }q8 |t3  
explicit bit_iterator() : m_container(0) F@4TD]E0^  
{ TU-aL  
m_size = 8*sizeof(Container); yiourR)H<  
m_index = m_size; `;X~$uS  
} by*?PhfF  
bool operator* () hh%f mc  
{ ]'  ck!eG  
char mask = 1; 0j@nOj(3  
char* pc = (char*)m_container; NOzAk%s3I  
int i   = (m_size-m_index-1)/8; & B CA  
int off   = (m_size-m_index-1)%8; VR5CRNBJ  
mask <<=off; YB;q5[  
return pc & mask; E;I'b:U`  
} .k_> BD];  
bit_iterator<Container>& operator++() [Un~]E.'J  
{ 6R`q{}.  
m_index++; ( L{>la!  
return *this; 9YMD[H\}V  
} A(j9T,!  
bit_iterator<Container>& operator++(int) Nj p?/r  
{ H{tG:KH  
m_index++; \Uz7ar#,  
return *this; [m*E[0Hu  
} seNJ6p=`  
bool operator==(bit_iterator<Container>& bitIt) pgp@Zw)r)k  
{ 2cnyq$4k  
return m_index == bitIt.m_index; \ytF@"7  
} {Yt@H  
bool operator!=(bit_iterator<Container>& bitIt) W##~gqZ/  
{ G8sxg&bf{  
return !(*this == bitIt); T(@J]Y-  
} \vKK q/f  
protected: :" ta#g'  
Container* m_container; Tgf\f%,h  
private: { /u}  
int m_size; g`n5-D@3  
int m_index; WVa-0;  
}; ktEdbALK  
p-qt?A  
用该迭代器可以将任意类型对象以二进制格式输出: KscugX*x  
double a = 10; ^8z~`he=_J  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

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