以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 SI%J+Y7
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 ,g?M[(wtc
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 0e]J2>
象当作char数组来处理。 >b3IZ^SB#$
template<class Container> >dF #1
class bit_iterator : public std::iterator<bidirectional_iterator_tag, { i3x\|
void, void> OEbZs-:
{ tVX|e2Y
public: cw~GH
explicit bit_iterator(Container& c) : m_container(&c) QJkiu8r
{ a04S&ezj
m_size = 8*sizeof(Container); o!y<:CGL
m_index = 0; HP 3%CB
} 6OPNP0@r
explicit bit_iterator() : m_container(0) !{uV-c-5,
{ w8>bct3@
m_size = 8*sizeof(Container); {BA Z`I
m_index = m_size; Of-gG~
} C`3fM05g
bool operator* () -ECnX/ "
{ 98<^!mwF
char mask = 1; c[OQo~m$
char* pc = (char*)m_container; M5`m5qc3
int i = (m_size-m_index-1)/8; /n,a0U/
int off = (m_size-m_index-1)%8; 6w{""K.{
mask <<=off; cY~lDLyB
return pc & mask; uSCI
} O,J,Q|`H&
bit_iterator<Container>& operator++() ov!L8
9`[u
{ lu1T+@t
m_index++; d]=>U^K
return *this; #&{)`+!"
} X/Fip0i
bit_iterator<Container>& operator++(int) Pm24;'
{ iHo0:J~
m_index++; (@\0P H0
return *this; zCwb>v
} F>@z&a}(
bool operator==(bit_iterator<Container>& bitIt) _J3\e%ys
{ W`wT0kP?*]
return m_index == bitIt.m_index; KHaYb5(a[
} u8y('\(
bool operator!=(bit_iterator<Container>& bitIt) 2@ZuH^qhk
{ CFY4PuI"!
return !(*this == bitIt); W$" >\A0%
} !$o9:[B
protected: @
eP[*Q
Container* m_container; AucX4J<
private: xxdxRy9/
int m_size; 1BzU-Ma
int m_index; "rQ?2?
}; )[t3-'
%=v<3
用该迭代器可以将任意类型对象以二进制格式输出: *q Ins/@
double a = 10; *nUa0Zg4q6
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));