以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 MN=
sIP,zk
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 }b["Jk\2
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 x4a:PuqmGG
象当作char数组来处理。 6er(% 4!
template<class Container> vC/[^
class bit_iterator : public std::iterator<bidirectional_iterator_tag, ?T:
jk4+
void, void> zjX7C~h^Q
{ ^DAa%u
public: ~KIDv;HSb[
explicit bit_iterator(Container& c) : m_container(&c) jkrx]`A{~
{ {GqXP0'
m_size = 8*sizeof(Container); zz$q5[n
m_index = 0; &;q<M_<
} NSLVD[yT
explicit bit_iterator() : m_container(0) `m%dX'0E
{ GSVdb/+
m_size = 8*sizeof(Container); `QP
~
m_index = m_size; {M~lbU
} V`a+Hi<P\
bool operator* () 2C+(":=}
{ U_z2J(e~
char mask = 1; T>]sQPg
char* pc = (char*)m_container; t)1phg4H)
int i = (m_size-m_index-1)/8; hY\{|
int off = (m_size-m_index-1)%8; p_terD:
mask <<=off; J0<p4%Cf
return pc & mask; f5dR 5G
} l`n5~Fs
bit_iterator<Container>& operator++() ]= x
1`j
{ q7]>i!A
m_index++; R e:T9K'e
return *this; /-*hjX$n
} 0~E 6QhV:
bit_iterator<Container>& operator++(int) DR+,Y2!_GT
{ \%_ZV9cKF
m_index++; r)l`
return *this; nTnRGf\T
} '
lo.h""
bool operator==(bit_iterator<Container>& bitIt) wgd<3 X
{ B1T5f1;uY
return m_index == bitIt.m_index; I^0t2[M
} R ZcH+?7
bool operator!=(bit_iterator<Container>& bitIt) 8cr NOZS6
{ xl!K;Y2<
return !(*this == bitIt); A]y*so!)>
} /#q")4Mf
protected: 2>y:N.
Container* m_container; Kr3];(w{
private: V2`;4d X*2
int m_size; 71iRG*O
int m_index; $AwZ2HY
}; ILG?r9x
m4**>!I
用该迭代器可以将任意类型对象以二进制格式输出: O2#S: ~h
double a = 10; :I/
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));