以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 _)s<E9t2N
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 ^UI{U1N~Bz
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 Pf&\2_H3s9
象当作char数组来处理。 .%) FK#s-
template<class Container> Y"~Tf{8
class bit_iterator : public std::iterator<bidirectional_iterator_tag, }z{2~ 0,
void, void> =kvfe" N0e
{ q
SR\=:$
public: faQ}J%a
explicit bit_iterator(Container& c) : m_container(&c) rMRM*`Q2
{ &4 Py
m_size = 8*sizeof(Container); k L\;90
m_index = 0; R
gY-fc0
} M#o.$+Uh
explicit bit_iterator() : m_container(0) -6lsR
{ zAT7^q^
m_size = 8*sizeof(Container); _Iz JxAcJ
m_index = m_size; *J[3f]PBmR
} }uWIF|h~
bool operator* () `K -j
{ ~2
L{m[s|
char mask = 1; ]7<}EG
char* pc = (char*)m_container; {
FVLH:{U^
int i = (m_size-m_index-1)/8; hx|Cam"
int off = (m_size-m_index-1)%8; Ln6\Iis
mask <<=off; #oBM A
return pc & mask; vv='.R, D
} 9G njJ
bit_iterator<Container>& operator++() ^s*j<fH
{ wz1fx>Q
m_index++; [:M:6JJ
return *this; !6y<