以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 `zHtfox!
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 +[9~ta|j
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 $;%-<*Co
象当作char数组来处理。 jNN$/ZWm
template<class Container> I"E5XVC);
class bit_iterator : public std::iterator<bidirectional_iterator_tag, NDhHU#Q9
void, void> WigC'
{ >JFAE5tj&2
public: ^f{+p*i}:
explicit bit_iterator(Container& c) : m_container(&c) tvptawA.
{ XljiK8q;%
m_size = 8*sizeof(Container); 93%U;0w[Nw
m_index = 0; M:OY8=V
} EA4aZ6%
explicit bit_iterator() : m_container(0) m,3?*0BMp=
{ cpB$b C](
m_size = 8*sizeof(Container); M:c^[9)y
m_index = m_size; WKZ9i2hcdf
} `LL#Ai a
bool operator* () M_V\mYC8I
{ M'D;2qo
char mask = 1; c"%XE#D
char* pc = (char*)m_container; 0-EhDGa]r
int i = (m_size-m_index-1)/8; F;jl0)fBR=
int off = (m_size-m_index-1)%8; OvU]|4h
mask <<=off; @R >4b
return pc & mask; +nRO<
} x+(h#+F
bit_iterator<Container>& operator++() Z>Nr"7k
{ $%VFk 53I
m_index++; y";{k+
return *this; pi? q<p%
} 8^ ;[c
bit_iterator<Container>& operator++(int) )`Tny]M
{ .:c^G[CQ^9
m_index++; 7|3Z+#|T
return *this; ):eX*
} *&>1A A
bool operator==(bit_iterator<Container>& bitIt) St/Hv[H'[E
{ Yt2_*K@rC
return m_index == bitIt.m_index; e J>(SkR:[
} ?gjM]Ki%:
bool operator!=(bit_iterator<Container>& bitIt) _ Onsfv
{ aYe,5dK>
return !(*this == bitIt); pL>Q'{7s3
} ,;C92XY
protected: y}ez js
Container* m_container; +L*2 6ar6
private: <FmrYwt
int m_size; =-{+y(<"r
int m_index; GAbX.9[V
}; v')Fq[H
t#oY|G3O}
用该迭代器可以将任意类型对象以二进制格式输出: `!5ZF@Q>e
double a = 10; Yd lXMddE
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));