以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 u#k,G`
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 Q$/F gS
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 E=lfg8yb:
象当作char数组来处理。 G;c0
template<class Container> k+GnF00N^8
class bit_iterator : public std::iterator<bidirectional_iterator_tag, }IkEyJsk
void, void> 4Xk;Qd
{ -01 1U!
public: f?^Oy!1]
explicit bit_iterator(Container& c) : m_container(&c) ^i)Q
CDU7
{ K |} ]<
m_size = 8*sizeof(Container); LY:?OGh
m_index = 0; UH&1c8y}
} RdvTtXg
explicit bit_iterator() : m_container(0) }6,bq`MN
{ exEld
m_size = 8*sizeof(Container); mYOdBd
m_index = m_size; Iki+5
} G[<[#$(
bool operator* () f(s3TLM
{ V& j.>Y
char mask = 1; A.C278^O8
char* pc = (char*)m_container; YEPG[W<kg
int i = (m_size-m_index-1)/8; Q1I_=fT
int off = (m_size-m_index-1)%8;
uC*:#[
mask <<=off; ""v`0OP&J
return pc & mask; Q @OC =
} lPcVhj6No%
bit_iterator<Container>& operator++() &J/4J
{ ZR-s{2sl
m_index++; ]1|Ql*6y,
return *this; rE{Xo:Cf
} /mBBeg^a
bit_iterator<Container>& operator++(int) r{B,uj"
{ fov=Yd!
m_index++; Rp`_Grcd
return *this; o=RqegL
} $,QpSK`9i
bool operator==(bit_iterator<Container>& bitIt) 3+8"
{ Y:"v=EhB
return m_index == bitIt.m_index; mQ^@ \s
} OBw`!G*w
bool operator!=(bit_iterator<Container>& bitIt) Vyt~OTI\
{ S-LZ(o{ZL
return !(*this == bitIt); s{z~Axup-
} u_6BHsU
protected: DNW2;i<hsz
Container* m_container; {r].SrW9s9
private: |DFvZ6}
int m_size; aO^:dl5
int m_index; @`kiEg'Q
}; :<t{ =0G
a:-)+sgHw
用该迭代器可以将任意类型对象以二进制格式输出: pe!dm}!h[
double a = 10; FfYd+]+?
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));