以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 rCE;'? Y
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 8[M*
x3
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 `dO}L
象当作char数组来处理。 ".E5t@ }?m
template<class Container> ywEDy|Wn$~
class bit_iterator : public std::iterator<bidirectional_iterator_tag, QF.3c6O@
void, void> _W |R;Cz]
{ gH'_ymT=
3
public: { V0>iN:~S
explicit bit_iterator(Container& c) : m_container(&c) 6|^0_6_
{ %9X{{_
m_size = 8*sizeof(Container); s@s/'^`
m_index = 0; \6:>{0\
} 2 h<U
explicit bit_iterator() : m_container(0) y@`~ 9$
{ b_l3+'#ofM
m_size = 8*sizeof(Container); wLUF v(&C
m_index = m_size; U{}!y3[wK
} Af9+HI
O
bool operator* () Px#$uU
{ (f~gEKcB2u
char mask = 1; uB;_vC
char* pc = (char*)m_container; &n|*uLn
int i = (m_size-m_index-1)/8; -;>#3O-
int off = (m_size-m_index-1)%8; \vVSh
mask <<=off; um[!|g/
return pc & mask; rrcwtLNbu
} MRs,l'
bit_iterator<Container>& operator++() sP y2/7Wqd
{ xs%LRF#u
m_index++; b=1%pX_
return *this; z,x"a
} 1ef'7a7e8
bit_iterator<Container>& operator++(int) w;+ br
{ AW/wI6[T
m_index++; (Y2mmd
return *this; J$QBI&D
} LN^UC$[tk
bool operator==(bit_iterator<Container>& bitIt) {zP#woz2Q
{ k"
YHsn
return m_index == bitIt.m_index; !| xZ6KV
} j{;|g%5t
bool operator!=(bit_iterator<Container>& bitIt) )* TF"
{ 9U^$.Lb
return !(*this == bitIt); QrC/ssf}
} k_?~<vTM
protected: Hbk&6kS
Container* m_container; ;'HF'Z
private: XsUUJuCG
int m_size; Yj|]Uff8O
int m_index; J &{xP8uq_
}; Obo _YE
eh<rRx"[
用该迭代器可以将任意类型对象以二进制格式输出: ]*;F. pZ
double a = 10; Go <'
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));