以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 S8*> kM'
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 Ygx,t|?7
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 5+FLSk
象当作char数组来处理。 ,I39&;Iq
template<class Container> DyX0xx^
class bit_iterator : public std::iterator<bidirectional_iterator_tag, {&`VGXG
void, void> FQ## 397
{ HXP;0B%4
public: ;.0LRWcJ
explicit bit_iterator(Container& c) : m_container(&c) b]K>vhQV
{ P CsK()
m_size = 8*sizeof(Container); V2QW\2@$
m_index = 0; 8bbVbP
} sy.:T]ZH
explicit bit_iterator() : m_container(0) >t,O2~
{ lbofF==(
m_size = 8*sizeof(Container); {_Np<r;j<
m_index = m_size; EOQaY
} qzlER
bool operator* () R_9 o!sTZ
{ I9,8HtnA
char mask = 1; <)J55++
char* pc = (char*)m_container; 0lf"w@/
int i = (m_size-m_index-1)/8; hG~ Uz
int off = (m_size-m_index-1)%8; cE2R r
mask <<=off; /xf.\Z7<
return pc & mask; C,3T!\
} /gX%ABmS
bit_iterator<Container>& operator++() 2+Vp'5>&
{ =ty2_6&>
m_index++; th90O|;
return *this; 'Dq"e$JM<
} d>~`j8,B
bit_iterator<Container>& operator++(int) v'$ykZ!Z
{ iI}nW
m_index++; WSSaZ9
=
return *this; g.=!3e&z%
} J:[3;Z
bool operator==(bit_iterator<Container>& bitIt) ~"\P~cg0J
{ LsnXS9_
return m_index == bitIt.m_index; E8
\\X
} vo.EM1x
bool operator!=(bit_iterator<Container>& bitIt) %K`4k.gN
{ }:"R-s
return !(*this == bitIt); vevx|<9,
} WE7>?H*Ro
protected: tPA"lBS !
Container* m_container; br10ptEx
private: gMCy$+?
int m_size; &4[<F"W>47
int m_index; vDWr|M%``l
}; -IGMl_s
x[Hhj'
用该迭代器可以将任意类型对象以二进制格式输出: rC~_:uXtE
double a = 10; p+!f(H
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));