以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 !\p-|51
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 A1i-QG/6
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 L/V3sSt
象当作char数组来处理。 ow+NT
template<class Container> 1W5YS +pf
class bit_iterator : public std::iterator<bidirectional_iterator_tag, sH6srwI
void, void> m|p}Jf!
{ }V`Fz',lZ
public: X]`\NNx
explicit bit_iterator(Container& c) : m_container(&c) 5^pQ=Sgt
{ =MMWcK&
m_size = 8*sizeof(Container); Xa-]+_?Q
m_index = 0; )U8F6GIC&}
} [<cP~
explicit bit_iterator() : m_container(0) b%AYYk)d?
{ X!r!lW
m_size = 8*sizeof(Container); O#9Q+BD
m_index = m_size; jk) U~KGcg
} /bg8oB4
bool operator* () 2H4+D)
{ x`a@h\n
char mask = 1; <OpiD%Ctx
char* pc = (char*)m_container; IWTD>c).
int i = (m_size-m_index-1)/8; Rb#?c+&#
int off = (m_size-m_index-1)%8; 5FzG_ w
mask <<=off; d@`yRueWiV
return pc & mask; #~(@Ka.eA0
} 0\u_\%[
bit_iterator<Container>& operator++() WpRi+NC}ln
{ |Y:T3hra61
m_index++; InRn!~_N
return *this; yl|+D]
} |IZG`3
bit_iterator<Container>& operator++(int)
c,x2
{ [4"%NY
m_index++; ^
.>)*P
return *this; 3&_(D)+
} g=a-zg9LX
bool operator==(bit_iterator<Container>& bitIt) A9F Z`
{ @"Do8p!*(6
return m_index == bitIt.m_index; ]kc]YO7i%R
} ^1}}-9q
bool operator!=(bit_iterator<Container>& bitIt) hX_;gR&R
{ D,]m7yFT
return !(*this == bitIt); &AA u:
} #~nI^
ggW
protected: vrh}X[JEw'
Container* m_container; O=ci"2!\-
private: ](^VEm}w;
int m_size; ==Ju2D?%
int m_index; f'*HP%+Y
}; >[ywrB ?T
julAN$2
用该迭代器可以将任意类型对象以二进制格式输出: {_PV~8u
double a = 10; R0 {+Xd
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));