以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 v;1F[?@3Y
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 sq /]wzT:
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 v4/-b4ET
象当作char数组来处理。 C#pZw[
template<class Container> Ucw yxXI
class bit_iterator : public std::iterator<bidirectional_iterator_tag, Rf-[svA
void, void> =}!Mf'
{ tiPa6tQ
public: ecJ6
explicit bit_iterator(Container& c) : m_container(&c) *LC+ PZV@
{ sJx+8
-
m_size = 8*sizeof(Container); m}
?rJ
m_index = 0; }R4c
} vxQ8t!-u
explicit bit_iterator() : m_container(0) u"xJjS
{ bvBHYf:^
m_size = 8*sizeof(Container); K4Dp:2/K%
m_index = m_size; BP[|nL
} revF;l6->C
bool operator* () SO\/-]9#
{ 07g':QU@
char mask = 1; zvc`3
char* pc = (char*)m_container; FyoEQ%.bI
int i = (m_size-m_index-1)/8; qml2XJ>
int off = (m_size-m_index-1)%8; ![6EUMx
mask <<=off; "t=hzn"~%
return pc & mask; QYb33pN|
} r,P1^ uHx
bit_iterator<Container>& operator++() V
D?*h
{ smY$-v)@
m_index++; "[p@tc?5
return *this; .9[45][FK
} 7IlOG~DC
bit_iterator<Container>& operator++(int) wd@aw /
{ m(iR|Zx
m_index++; 69y;`15
return *this; A=zPLq{Sb
} W=B"Q
qL
bool operator==(bit_iterator<Container>& bitIt) 2?C`4AR[2H
{ \vfBrN
return m_index == bitIt.m_index; -~" :f8
} d@0Kr5_
bool operator!=(bit_iterator<Container>& bitIt) y4:H3Sk
{ VQI(Vp|
return !(*this == bitIt); {%v-(
} x3ERCqTR
protected: f
).1]~
Container* m_container; vP@v.6gS,
private: e(F42;$$
int m_size; zjL.Bhiud
int m_index; RE$`YCs5
}; O#EV5FeF.
e,_-Je
用该迭代器可以将任意类型对象以二进制格式输出: Fk;oE'"D
double a = 10; DD9 ?V}Yx
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));