以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构
` @nl
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 #B4%|v;`E?
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 EK4d_L]I
象当作char数组来处理。 :Nz9xD$S5
template<class Container> \[y`'OD~
class bit_iterator : public std::iterator<bidirectional_iterator_tag, gLOEh6
void, void> oH_;4QU4y
{ rx] @A
public: .ev?"!Vpp9
explicit bit_iterator(Container& c) : m_container(&c) E{|W(z,
{ ,^C--tgZJg
m_size = 8*sizeof(Container); EM[WK+9>I{
m_index = 0; u:=7l
} Ymg|4%O@
explicit bit_iterator() : m_container(0) #3gp6*R
{ NuQdSj_>
m_size = 8*sizeof(Container);
iKT [=c
m_index = m_size; h2XfC.f
} y !_C/!d
bool operator* () ]7RD"}
{ >Z'NXha
char mask = 1; ]x(!&y:h
char* pc = (char*)m_container; V=o
t-1,j7
int i = (m_size-m_index-1)/8; a6uJYhS~
int off = (m_size-m_index-1)%8; eS~LF.^Jw
mask <<=off; UWd=!h^dt
return pc & mask; $w`=z<2yo1
} Y2~nBb
bit_iterator<Container>& operator++() 67Th;h*sh
{ toBHkiuD
m_index++; (2$p{Uf
return *this; |R/%D%_g
} -#N.X_F
bit_iterator<Container>& operator++(int) +l<5#pazx
{ |xdsl,
m_index++; /7Cc#P6
return *this; ]QlwR'&j/n
} woGAf)vV#
bool operator==(bit_iterator<Container>& bitIt) Y,^@P
{ 7%x[q}
return m_index == bitIt.m_index; :LW4E9O=H
} :&V h?
bool operator!=(bit_iterator<Container>& bitIt) 1SCR.@k<
{ 4R1<nZ"e~
return !(*this == bitIt); 0dE@c./R i
} RAgg:3^
protected: #W4dkCd(pF
Container* m_container; F%@aB<Nu
private: 'h|DO/X~L
int m_size; 3q\,$*D.
int m_index; o$jLzE"
}; dMv=gdY
:VRNs
用该迭代器可以将任意类型对象以二进制格式输出: !Prg_6
`
double a = 10; R{<kW9!
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));