以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 )FSEHQ
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 -u7NBtgUh
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 .SLpgYFL{
象当作char数组来处理。 k }{o:
N
template<class Container> \H9:%Tlp~4
class bit_iterator : public std::iterator<bidirectional_iterator_tag, l-P6B9e|\
void, void> &Yo|Pj
{ NG`Y{QT6N
public: P,xIDj4d
explicit bit_iterator(Container& c) : m_container(&c) &6vWz6 !P
{ x]@z.Yj
m_size = 8*sizeof(Container); t3!OqM
m_index = 0; u0]u"T&N!
} /OYa1,
explicit bit_iterator() : m_container(0) %NfXe[T
{ 5dhy80|g]
m_size = 8*sizeof(Container); PD^G$LT
m_index = m_size; 'oK oF
} r{B28'f[
bool operator* () WNZYs
{ N:CQ$7T{ j
char mask = 1; Bd7B\zM
char* pc = (char*)m_container; p_
f<@WE
int i = (m_size-m_index-1)/8; xXc>YTK'
int off = (m_size-m_index-1)%8; &CcW(-
mask <<=off; [V>s]c<4`o
return pc & mask; m)LI|
v
} )t@9!V
bit_iterator<Container>& operator++() :<mJRsDf
{ "GR*d{
m_index++;
q)f_!N
return *this; hv?T}E
} ,Tu.cg
bit_iterator<Container>& operator++(int) @?3^Ks_
{ i]N<xcF9N*
m_index++; kG{};Vm
return *this; 3tCTPZy
} l
S3LX
bool operator==(bit_iterator<Container>& bitIt) /a<UKh:A[
{ 6%h%h: e
return m_index == bitIt.m_index; x.Egl4b3
} nGe4IY\-w
bool operator!=(bit_iterator<Container>& bitIt) Z'>UR.g
{ 2m]4
return !(*this == bitIt); KS<@;Tt
} p"c6d'qe
protected: s9a`2Wm
Container* m_container; H la?\
private: 4].o:d;`/
int m_size; vBOY[>=
int m_index; J4"A6`O
}; Y,GlAr s4
?ueL'4Mm
用该迭代器可以将任意类型对象以二进制格式输出: tq~4W% p/
double a = 10; _@y uaMoW=
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));