以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 h7P<3m}
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 s3/iG37K
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 +55+%oGl
象当作char数组来处理。 M+L8~BD@
template<class Container> S"@/F-
81
class bit_iterator : public std::iterator<bidirectional_iterator_tag, >1$vG
void, void> :Rroz]*
{ l%_r 3W
public: N|rB~
explicit bit_iterator(Container& c) : m_container(&c) baO'FyCs9&
{ 9cnLf#
m_size = 8*sizeof(Container); yrF"`/zv6|
m_index = 0; x 8/I"!gI
} LmZ"_
explicit bit_iterator() : m_container(0) Y'{F^VxA/
{ W"v"mjYud
m_size = 8*sizeof(Container); ^.pd'
m_index = m_size; +_T`tmQ
} lz [s
bool operator* () @2`$ XWD
{ }eK.\_t=
char mask = 1; +T/T \[
char* pc = (char*)m_container; 1iJa j
int i = (m_size-m_index-1)/8; &)$}Nk
int off = (m_size-m_index-1)%8; /Xm4%~b_gj
mask <<=off; MS~+P'
return pc & mask; JW}O`H9
} +V `*
bit_iterator<Container>& operator++() %K[u
{ W7` fI*lc
m_index++; ,\RZ+kC>~
return *this; s# 9*`K
} pQNTN.L9NZ
bit_iterator<Container>& operator++(int) -<{;.~nI.
{ u85dG7
m_index++; cuoZ:Wh
return *this; '* eeup
} b6?&h:{k
bool operator==(bit_iterator<Container>& bitIt) (MGYX_rD
{ EY^+ N>
return m_index == bitIt.m_index; vve L|j
} BW x=Q
bool operator!=(bit_iterator<Container>& bitIt) ):-Ub4A\
{ *A([1l&]i
return !(*this == bitIt); pGdFeEkB/
} "qdEu KI
protected: %F}i2!\<L
Container* m_container; m>9j dsqB
private: 9SQcChG~j
int m_size; fZgEJsr
int m_index; L}\ oFjVju
}; EM7Z g 65
b[rVr
J
用该迭代器可以将任意类型对象以二进制格式输出: a{@gzB
double a = 10; Db K(Rh_
K
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));