以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 qgs:9V
xF
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 ]DUmp6
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 '=H3Y_{oO
象当作char数组来处理。 4j}.=u* X7
template<class Container> G%junS'zt
class bit_iterator : public std::iterator<bidirectional_iterator_tag, l1.eAs5U
void, void> ?pdN!zOeL
{ SBaTbY0
public: E9 w"?_A)
explicit bit_iterator(Container& c) : m_container(&c) _aU
:[v*!
{ Vp1 Q^`a{G
m_size = 8*sizeof(Container); J vl-=~
m_index = 0; 4}Y? :R
} RT2&^9-
explicit bit_iterator() : m_container(0) cJ>^@pd{
{ j*FpQiBoT
m_size = 8*sizeof(Container); Ax 4R$P.]u
m_index = m_size; sZwa#CQK q
} ?k=)T]-}
bool operator* () "u'dd3!
{ lmIphOUoIw
char mask = 1; np\*r|U
char* pc = (char*)m_container; 1wE`kbC<
int i = (m_size-m_index-1)/8; wH\
K'/
int off = (m_size-m_index-1)%8; M=fhRCUB
mask <<=off; BwYR"
return pc & mask; =y^g*9}_
} "HLh3L~
bit_iterator<Container>& operator++() P
V9q=
{ x}f)P
m_index++; <J]N E|:
return *this; iA4VT,
} {M23a
_t\
bit_iterator<Container>& operator++(int) - v=ndJ.
{ SbobXTbG
m_index++; 6|Crc$4l
return *this; :2lM7|@/
} AY]rQ:I
bool operator==(bit_iterator<Container>& bitIt)
T2t o!*T
{ ?U,Xy xN
return m_index == bitIt.m_index; orEb+
} G&yF9s)Lvs
bool operator!=(bit_iterator<Container>& bitIt) [3]h(D
{ G[ q<P
return !(*this == bitIt); 6f
J5Y
iQ
} _Ry
protected:
V'AZs;
Container* m_container; <2\QY
private: s="cg0PD
int m_size; P!/:yWd
int m_index; n* z;%'0
}; 'fIG$tr9X
<$%Y#I'zX
用该迭代器可以将任意类型对象以二进制格式输出: I -XkxDw
double a = 10; 6 w0r)
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));