以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 p}%T`e=Z9
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 fGDR<t3yiQ
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 ^| L@f
象当作char数组来处理。 (5y+g?9d;
template<class Container> *6oQW
class bit_iterator : public std::iterator<bidirectional_iterator_tag, 3A'vq2beM
void, void> '`$z!rA
{ _Gv[ D
public: bLyU;
explicit bit_iterator(Container& c) : m_container(&c) \M-}(>Pfk
{ rnvKfTpZDU
m_size = 8*sizeof(Container); iO)FZ%?"
m_index = 0; w,fA-*bZ 0
} 5(0f"zY
explicit bit_iterator() : m_container(0) ]03+8#J
{ Ww&~ZZZ {
m_size = 8*sizeof(Container); T2-n;8t
m_index = m_size; WV]%llj^
} *5'U3py
bool operator* () EY=`/~|c
{ spIkXEK
char mask = 1; a[;TUc^I1F
char* pc = (char*)m_container; /g}2QmvH
int i = (m_size-m_index-1)/8; TxL;qZRY
^
int off = (m_size-m_index-1)%8; eYd6~T[9
mask <<=off; Enu/Nj 2
return pc & mask; Uf#.b2]
} R4+Gmx1
bit_iterator<Container>& operator++() o";5@NH
{ 0Q^ -d+!
m_index++; 69#D,ME?
return *this; n#,<-Rb-
} nA:\G":\y
bit_iterator<Container>& operator++(int) <BoDLvW>
{ egcJ@Of
m_index++; Ml`tDt|;
return *this; jiS|ara"
} ]B'Ac%Rx
bool operator==(bit_iterator<Container>& bitIt) NV 6kj=r
{ vK\n4mE[,
return m_index == bitIt.m_index; ;8z40cD
} `NIc*B4q.
bool operator!=(bit_iterator<Container>& bitIt) "RPX_
{ )c
vA}U.z
return !(*this == bitIt); >_3+s~
} ATq)8Rm\
protected: >iefEv\
Container* m_container; .kO!8Q-;%
private: kkfwICBI
int m_size; bo^d!/;
int m_index; @* a'B=7
}; gY'w=(/`
d5?"GFy
用该迭代器可以将任意类型对象以二进制格式输出: HF@K$RPK
double a = 10; C1
qyjlR
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));