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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 2,^ > lY  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 /y|ZAN  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 X Q CE`m  
象当作char数组来处理。 cB36w$n8  
template<class Container> gs=ok8w  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, "C(yuVK1G  
void, void> ru6M9\h*  
{ R MOs1<D  
public: VW*?(,#j{  
explicit bit_iterator(Container& c) : m_container(&c) cvE)  
{ kjB'W zZ8  
m_size = 8*sizeof(Container); Qe-Pg^PS]  
m_index = 0; D~Ef%!&  
} pzoh9}bue  
explicit bit_iterator() : m_container(0) 1P'A*`!K  
{ 'Bxj(LaV-  
m_size = 8*sizeof(Container); /GM!3%'=  
m_index = m_size; {2m F\A#.  
} #:P$a%V  
bool operator* () ngmC~l*,  
{ !]Qk?T~9-  
char mask = 1; B~| ]gd  
char* pc = (char*)m_container; f6Lc"b3s1  
int i   = (m_size-m_index-1)/8; #5kclu%L$  
int off   = (m_size-m_index-1)%8; *uf)t,%  
mask <<=off; >;R`Q9s7  
return pc & mask; GB<.kOGQ[  
} { Ie~MW  
bit_iterator<Container>& operator++() Di27=_J  
{ d*VvQU8C  
m_index++; ryw%0H18  
return *this; N)Q.P'`N  
} g5"I{ol5T~  
bit_iterator<Container>& operator++(int) ')~V=F  
{ t'0&n3  
m_index++; UNwjx7usD  
return *this; BDzAmrO<  
} =S\^j"  
bool operator==(bit_iterator<Container>& bitIt) hN~H8.g  
{ '+ZJf&Ox  
return m_index == bitIt.m_index; b 9"t%R9/Q  
} UN F\k1[  
bool operator!=(bit_iterator<Container>& bitIt) ^Ifm1$X}  
{ U<Qi`uoj!  
return !(*this == bitIt); +N7<[hE;  
} lJ]QAO  
protected: K*2s-,b *  
Container* m_container; Eb@**%  
private: n4M Xa()P1  
int m_size; 3e47UquZ  
int m_index; {.p;V  
}; hkm}oYW+  
%&VI-7+K  
用该迭代器可以将任意类型对象以二进制格式输出: ujkWVE'  
double a = 10; _b>{:H&\  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

您目前还是游客,请 登录注册
温馨提示:欢迎交流讨论,请勿纯表情、纯引用!
认证码:
验证问题:
3+5=?,请输入中文答案:八 正确答案:八