以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 39i9wrP
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 /+]s.V.
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 s
+s" MI
象当作char数组来处理。 C.Uju`3
template<class Container> pB:$lS
class bit_iterator : public std::iterator<bidirectional_iterator_tag, b1#dz]
void, void> e [h8}F
{ #Pk$L+C
public: =EP13J
explicit bit_iterator(Container& c) : m_container(&c) K=::)/{P
{ zYER
m_size = 8*sizeof(Container); lSwcL
m_index = 0; _fk#<
} &53]sFZ
explicit bit_iterator() : m_container(0) 3VO2,PCZ
{ W_|0y4QOo
m_size = 8*sizeof(Container); 0%Ll
m_index = m_size; .Pndx%X9s
} Jju#iwb
bool operator* () `fNpY#QsN
{ xw5d|20b
char mask = 1; A7_4.VH
char* pc = (char*)m_container; 9A'Y4Kg<C
int i = (m_size-m_index-1)/8; ?%tMohL
int off = (m_size-m_index-1)%8; C4$:mJ>y
mask <<=off; Sl2iz?
return pc & mask; 1T&Rc4$Sn7
} jKIxdY:U
bit_iterator<Container>& operator++() b}^S.;vNj
{ LpbsYl
m_index++; @$^bMIj@W
return *this; DTRJ/@t
} o G*5f
bit_iterator<Container>& operator++(int) G3P&{.v
{ /6uT6G+(z}
m_index++; LkruL_E>
return *this; &)wiKh"$
} }Db[ 4
bool operator==(bit_iterator<Container>& bitIt) 3g'S\G@
{ s8"8y`u
return m_index == bitIt.m_index; {P%9
} yF}OfK?0f
bool operator!=(bit_iterator<Container>& bitIt) ))kF<A_MK
{
zG }?
return !(*this == bitIt); ;ea]$9
} z;f2*F
protected: pIV-kI:w
Container* m_container; olB)p$aH#
private: 1@48BN8cm'
int m_size; )>
,wj
int m_index; d_UN0YT<
}; B(a-k?
ia&AW
用该迭代器可以将任意类型对象以二进制格式输出: (_kp{0r#
double a = 10; e~%
;K4
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));