以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 A8AeM`
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 3hzz*9/n
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 p!<PRms@
象当作char数组来处理。 o>m*e7l,
template<class Container> TQ[J,
class bit_iterator : public std::iterator<bidirectional_iterator_tag, ~(`MP<
void, void> $?LegX
{ CwyE8v
public: rTJ;s
explicit bit_iterator(Container& c) : m_container(&c) -b?s\X
{ IEI&PRD
m_size = 8*sizeof(Container); vAOThj)
m_index = 0; }wJH@'0+
} u%OLXb
explicit bit_iterator() : m_container(0) &b-&0rTqz
{ hVJ}EF0
m_size = 8*sizeof(Container); "tDB[?
m_index = m_size; g"g3|$#Ej|
} >{Xyl):
bool operator* () 3J3wKw!`
{ <u?\%iJ"
char mask = 1; _BCq9/
char* pc = (char*)m_container; ws
U @hqS
int i = (m_size-m_index-1)/8; GK3cQw
int off = (m_size-m_index-1)%8; ;:Tb_4Hr
mask <<=off; 6!=q+sw/X
return pc & mask; 1.Neg|
} 3S%/>)k
bit_iterator<Container>& operator++() 6.|[;>Km
{ $2Bll 5!]
m_index++; '=Acg"aT
return *this; tvUC d}
} ~ET XXu${I
bit_iterator<Container>& operator++(int) o,$K=#Iv
{ ITz+O=I4R]
m_index++; &,\my-4c>
return *this; `y{[e j
} /7ykmW
bool operator==(bit_iterator<Container>& bitIt) Ak3V< =gx
{ /8 "rCh|m-
return m_index == bitIt.m_index; FgR9$ is+
} u!t<2`:h
bool operator!=(bit_iterator<Container>& bitIt) :8]y*j
{ @z=L\e{
return !(*this == bitIt); *{O[}
} vu:] [2"0
protected: Sb }=j;F
Container* m_container; 0L d"df*
private: .
\8"f]~
int m_size; v"_E0
3!
int m_index; EQ>@K-R
}; cXb&Rm'L
9vCCE[9
用该迭代器可以将任意类型对象以二进制格式输出: k/)h @K8@
double a = 10; WfYG#!}x
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));