以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 +EjXoW7V
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 OK v2..8
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 O[= L#wi
象当作char数组来处理。 cBqbbZyUk
template<class Container> [R1|=kGU
class bit_iterator : public std::iterator<bidirectional_iterator_tag, ~S<aIk0l
void, void> 842v^ 2
{ lusUmFm'*
public: Y2tVq})!
explicit bit_iterator(Container& c) : m_container(&c) C9?mxa*z
{ Wu*
4r0
m_size = 8*sizeof(Container); "Y^j=?1k
m_index = 0; Mi#i 3y(
} Xg]Cq"RJC
explicit bit_iterator() : m_container(0) U2?R&c;b
{ $)@D(m,ybd
m_size = 8*sizeof(Container); @;Jv/N6@
m_index = m_size; kJl^,q
} u=Ik&^v
Wq
bool operator* () s<"|'~<n
{ h2x9LPLBxT
char mask = 1; PX/Y?DP
char* pc = (char*)m_container; ?o.d FKUe
int i = (m_size-m_index-1)/8; 5qH*"i+|s
int off = (m_size-m_index-1)%8; ]QHp?Ii1
mask <<=off; Q*I8RAfd
return pc & mask; ;<m*ASM.3
} lCUYE"o
bit_iterator<Container>& operator++() \,Ws=9f
{ qJT/48lf_
m_index++; 7'esJ)2
return *this; AB\Ya4O"9
} a(6h`GHo
bit_iterator<Container>& operator++(int) &-qQF`7
{ (_4DZMf
m_index++; pl3ap(/
return *this; 9vyf9QE;
} wdP(MkaV
bool operator==(bit_iterator<Container>& bitIt) 6d/Q"As
{ b
MD|
return m_index == bitIt.m_index; r!fUMDS
} 5b/ ~]v
bool operator!=(bit_iterator<Container>& bitIt) E \DA3lq
{ BVeMV4
return !(*this == bitIt); wHs1ge (
} o$</At
protected: Le?g,c
Container* m_container; 8cOft ;|qB
private: 'm~=sC_uL
int m_size; sw}O g`U
int m_index; Wgh@X B
}; S=-$:65
;<Z6Y3>I8
用该迭代器可以将任意类型对象以二进制格式输出: k*)sz
double a = 10; Kw`CN
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));