以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 i9V,
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 jcjl q-x
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 wz{c;v\J^
象当作char数组来处理。 *CbV/j"P?
template<class Container> _[Sh`4`r
class bit_iterator : public std::iterator<bidirectional_iterator_tag, Ms5R7<O.7
void, void> _2)QL
{ ?o`:V|<v
public: R](cko=
explicit bit_iterator(Container& c) : m_container(&c) =Ot_P7'5gv
{ Gx4{ 9
m_size = 8*sizeof(Container); )TyP{X>
m_index = 0; ]omBq<ox'Y
} 'vYt_T
explicit bit_iterator() : m_container(0) !]5V{3
{ 17`-eDd
m_size = 8*sizeof(Container); M`8c|*G
m_index = m_size; hd,O/-m#
} cnRgzj<ek
bool operator* () bvHQ #:}H
{ bR1Q77<G\
char mask = 1; 7F_N{avr
char* pc = (char*)m_container; kZ]pV=\Y*
int i = (m_size-m_index-1)/8; ;@:-T/=
int off = (m_size-m_index-1)%8; jP0TyhM
mask <<=off; eKLE^`2*@
return pc & mask; l_8ibLyo
} F@#p
bit_iterator<Container>& operator++() .XVL JJ#
{ 4#.Q|vyl]"
m_index++; mg>wv[ 7
return *this; P!IXcPKW53
} 2aX{r/Lc
bit_iterator<Container>& operator++(int) )=bW\=[8
{ 4@Z!?QzW
m_index++; ks
%arm&
return *this; :t;i2Ck
} -3y
bool operator==(bit_iterator<Container>& bitIt) V#+F*w?&D
{ d(@ ov^e-
return m_index == bitIt.m_index; yW\kmv.O
} _3NH"o
d
bool operator!=(bit_iterator<Container>& bitIt) 1~},}S]id
{ !qHB?]
return !(*this == bitIt); yjq|8.L[
G
} 7Ka4?@bQ
protected: 6#.9T;&
Container* m_container; H<;~u:;8Q
private: cct/mX2&~
int m_size; .6I'V3:Kg
int m_index; :h/v"2uDN
}; G:wO1f6
3OY(L`
用该迭代器可以将任意类型对象以二进制格式输出: p:eaZ
double a = 10; #/8
Nav
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));