以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 puZ<cV
e/
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 u+I-!3J87
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 &0(2Z^Z>fw
象当作char数组来处理。 *9j9=N?
template<class Container> d2.n^Q"?3
class bit_iterator : public std::iterator<bidirectional_iterator_tag, *n}9_V%
void, void> xBgf)'W_Z
{ g+ 2SB5 2D
public: R^1= :<)C
explicit bit_iterator(Container& c) : m_container(&c)
`c :'il?
{ Ic#+*W\ZW
m_size = 8*sizeof(Container); \RQ5$!O
m_index = 0; LTzf&TZbx5
} ;Ic3th%u
explicit bit_iterator() : m_container(0) YLSG
5vF+
{ }{K)5k@
m_size = 8*sizeof(Container); L'aMXNO
m_index = m_size; =_^g]?5i
} JYv&I t
bool operator* () D|e 6$O5o
{ /jj!DO#
char mask = 1; ?ZDx9*f
char* pc = (char*)m_container; U-WrZ|-
int i = (m_size-m_index-1)/8; X\1D[n:
int off = (m_size-m_index-1)%8; M\`6H8aLn
mask <<=off; fi bR:8
return pc & mask; D|=QsWZI
} 6\::Ku4_2
bit_iterator<Container>& operator++() y:2o-SJn
{ DU 8)c$
m_index++; e}K;5o=I
return *this; 0HNe44oI+D
} \s~W;m
bit_iterator<Container>& operator++(int) kQ'G+Kw~F
{ 9 z3Iwl
m_index++; X,y$!2QI
return *this; |?g2k:fzB7
} ^eZqsd8a
bool operator==(bit_iterator<Container>& bitIt) 8i:b~y0
{ m|f|u3'z$
return m_index == bitIt.m_index; 9R ugkGy
} VKR6 i
bool operator!=(bit_iterator<Container>& bitIt) Q45rP4mQ
{ 2l\Oufer"
return !(*this == bitIt); G 8NSBaZe
} .pdgRjlSn
protected: As)-a5!
Container* m_container; @l;f';+
private: mS%D"
e
int m_size; j;+nnpg
int m_index; lcUL7
}; f3596a
g8qN+Gg
用该迭代器可以将任意类型对象以二进制格式输出: kXOlZC
double a = 10; CV&
SNA
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));