以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 "T7>)fbu
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 Y([d;_#P
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 =HS4I.@c_5
象当作char数组来处理。 [ZD[a6(94
template<class Container> Y[@0qc3UO
class bit_iterator : public std::iterator<bidirectional_iterator_tag, jQ|:I7y
void, void> Q(e{~
]*
{ (xu=%
public: C B/r]+4
explicit bit_iterator(Container& c) : m_container(&c) J+|/-{g
{ -x{&an=
m_size = 8*sizeof(Container);
%A)538F
m_index = 0; t0.;nv@A0
} #3+~.,X9
explicit bit_iterator() : m_container(0) 0p `")/
{ NV6G.x
m_size = 8*sizeof(Container); _4v"")Xe
m_index = m_size; gHZqA_*T8U
} O:IQ!mzV5
bool operator* () o<rsAe
{ H{%H^t>
char mask = 1; WL1\y|
char* pc = (char*)m_container; $ser+Jt=
int i = (m_size-m_index-1)/8; ceG&,a$\
int off = (m_size-m_index-1)%8; A?r^V2+j
mask <<=off; *gDl~qNRoS
return pc & mask; NH4?q!'G
} SO_>c+Dw
bit_iterator<Container>& operator++() qe%V#c
{ #Kl}= 1
4
m_index++; '%&z.{
return *this; @vt$MiOi
} N571s
bit_iterator<Container>& operator++(int) ,56;4)cv
{ WqQU@sA
m_index++; l `R KqT+
return *this; /NU103F yt
} 5gshKmt_
bool operator==(bit_iterator<Container>& bitIt) V&iS~V0.
{ PS}73Y#
return m_index == bitIt.m_index; {OP~8e"
} zN")elBi
bool operator!=(bit_iterator<Container>& bitIt) ?
|VysJ
{ e2wvc/gG6
return !(*this == bitIt); F&az":
} h/?6=D{
protected: SY T$3|a
Container* m_container; ;MPKJS68@
private: 9go))&`PJL
int m_size; oj@g2H5P
int m_index; " #v%36U
}; 3[VNsX
Sc_5FX\Yx
用该迭代器可以将任意类型对象以二进制格式输出: `HyF_m>\
double a = 10; i*CnoQH
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));