以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 P,,@&*
:
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 &Uzg&eB
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 e\\ I,
象当作char数组来处理。 /H}83 C
template<class Container> ?:UDK?
class bit_iterator : public std::iterator<bidirectional_iterator_tag, p`Ax)L\f
void, void> `2GHB@S"k
{ nL\BB&
public: [^aow-4z
explicit bit_iterator(Container& c) : m_container(&c) y%43w4
{ ,;UVQwY
m_size = 8*sizeof(Container); Qp{{OjD
m_index = 0; ~~>D=~B0'
} >YD?
pDPb/
explicit bit_iterator() : m_container(0) d6wsT\S
{ [03Aej
m_size = 8*sizeof(Container); i/~A7\:8%
m_index = m_size; x#'#
~EO-G
} /I="+
bool operator* () P.LMu
{ vX&Nh"0H&
char mask = 1; EFV'hMjS)
char* pc = (char*)m_container; ?FD^S~bz-
int i = (m_size-m_index-1)/8; {]`O $S
int off = (m_size-m_index-1)%8; $dq
R]'
mask <<=off; e3&R3{
return pc & mask; {5:y,=Y
} &d=j_9
bit_iterator<Container>& operator++() YMC*<wXN
{ |]^OX$d
m_index++; F?TAyD*
return *this; 5_{C \S`T
} wQDKv'zU1
bit_iterator<Container>& operator++(int) 1)H+iN|im/
{ {i3]3V"Xp
m_index++; LY/K,6^a
return *this; /z`LB
} <!R~G-D#_T
bool operator==(bit_iterator<Container>& bitIt) 0zetOlFbO
{ $GEY*uIOa
return m_index == bitIt.m_index; GoZr[=d
} NEJxd%-
bool operator!=(bit_iterator<Container>& bitIt) zaa>]~g .
{ Ee d2`~
return !(*this == bitIt); ux'!1mN
} r:<UV^; 9l
protected: X&pK#=
Container* m_container; E\ 5t&jZr
private: !Mceg
int m_size; |I6\_K.=L
int m_index; WM~@/J
}; 2{% U\^-
dk# LAm0<
用该迭代器可以将任意类型对象以二进制格式输出: NO8)XJ3s
double a = 10; #1+1 q{=Z<
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));