以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 dx.,
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 (Ci{fY6`
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 PQ0l <]Y
象当作char数组来处理。 T> < Vw
template<class Container> 3)ZdT{MY
class bit_iterator : public std::iterator<bidirectional_iterator_tag, '!V5 #J
void, void> a ](Jc)
{ +KcD Y1[
public: (9!/bX<
explicit bit_iterator(Container& c) : m_container(&c) J 7/)XS
{ O,D/&0
m_size = 8*sizeof(Container); sJ3O ]
m_index = 0; 9y$"[d27;+
} \>7hT;Av=G
explicit bit_iterator() : m_container(0) Id(wY$C&>
{ ;:`0:Ao.
m_size = 8*sizeof(Container); 7^hwRZJ{
m_index = m_size; L/+KY_b:*
} R3dt-v
bool operator* () =Rw-@*#l
{ N!=$6`d
char mask = 1; E0lro+'lS
char* pc = (char*)m_container; Fcp8RBq
int i = (m_size-m_index-1)/8; >Nho`m(
int off = (m_size-m_index-1)%8; _=g;K+%fb
mask <<=off; Nn:>c<[
return pc & mask; Qzh`x-S
} HLruZyN4
bit_iterator<Container>& operator++() ^_0l(ke
{ .29y3}[PO
m_index++; "TQ3{=j{
return *this; WU:r:m+
>
} cs\/6gSCo
bit_iterator<Container>& operator++(int) G&DL)ePu]m
{ No(p:Snbo
m_index++; j~#nJI5]
return *this; O9/7?"l"
} s0/[mAY
bool operator==(bit_iterator<Container>& bitIt) "'9[c"Iz
{ I `I+7~t
return m_index == bitIt.m_index; \~4IOu
} 2$@N4
bool operator!=(bit_iterator<Container>& bitIt) F?jFFwim
{ x[m&ILr
return !(*this == bitIt); F-&=N {+
} $KAOJc4<
protected: B{dR/q3;@
Container* m_container; %]iE(!>3oy
private: VKtZyhK"h
int m_size; 'U|Tye i?
int m_index; g q`S`
}; wBaIN]Y,
KJQW ))%e
用该迭代器可以将任意类型对象以二进制格式输出: 7#G8qh<
double a = 10; ))xyaYIZkk
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));