以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 v3b[08
F
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 ]Lc:M'V#
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 ]ne&`uO
象当作char数组来处理。 P4"Pb\o*
template<class Container> 'r KDw06/
class bit_iterator : public std::iterator<bidirectional_iterator_tag, g.AMCM?z
void, void> )@-v6;7b0
{ _%g}d/v}pO
public: Ka[@-XH
explicit bit_iterator(Container& c) : m_container(&c) (TufvHC
{ \Y)pm9!
m_size = 8*sizeof(Container); oY!nM%z/
m_index = 0; Wa#!O$u
} Qr`WPTQr"
explicit bit_iterator() : m_container(0) 9zdp8?T
{ C4Pi6.wf
m_size = 8*sizeof(Container); # 2As-9
m_index = m_size; 2?3D`
`
} ML6V,V/e
bool operator* () i^c
{ !olvP*c"
char mask = 1; Yjv[rH5v
char* pc = (char*)m_container; f
wN
int i = (m_size-m_index-1)/8; ahagt9[,:F
int off = (m_size-m_index-1)%8; gTz66a@i
mask <<=off; &!I^m
return pc & mask; xkv2#"*v
} wJ_E\v P
bit_iterator<Container>& operator++() )9~1XiS,
{ OrXx0Hn
m_index++; 7%p[n;-o&
return *this; i
! wzID
} =^.f)
bit_iterator<Container>& operator++(int) nSH
A,c
{ [al, UO
m_index++; #"}Z'|X*
return *this; s:
c
} yZf+*j/a7
bool operator==(bit_iterator<Container>& bitIt) (<ybst6+I
{ */gm! :Ym
return m_index == bitIt.m_index; az7<@vSXi
} 9Y:JA]U&8
bool operator!=(bit_iterator<Container>& bitIt) 65FdA-4
{ iz'#K?PF_
return !(*this == bitIt); } D5*
} qaBjV6loy
protected: &KfRZ`9H
Container* m_container; #JAU5d
private: (bfHxkR.
int m_size; D#>+]}5@x
int m_index; pdnkHR$
}; Xg*IOhF6x
4l! ^"=rh
用该迭代器可以将任意类型对象以二进制格式输出: 3c5=>'^F
double a = 10; xyO]Evg
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));