以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 C"y(5U)d
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 p'Y^X
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 })'B<vq
象当作char数组来处理。 ,V7nzhA2
template<class Container> 0j^Kgx
class bit_iterator : public std::iterator<bidirectional_iterator_tag, B`EJb71^Xy
void, void> Lc}LGq!
{ 9=s<Ld
public: ko!)s
explicit bit_iterator(Container& c) : m_container(&c) kXViWOXU^
{ EfqX
y>W
m_size = 8*sizeof(Container); [CY9^N
m_index = 0; v_yw@
} t$` r4Lb9/
explicit bit_iterator() : m_container(0) &j;wCvE4+
{ ___~D
dq
m_size = 8*sizeof(Container); Mc) }\{J
m_index = m_size; aEB_#1
} <;lkUU(WT2
bool operator* () b]e"1Y)D-
{ &1Ok`_plO
char mask = 1; )j6~Wy@4
char* pc = (char*)m_container; ]>!K3kB
int i = (m_size-m_index-1)/8; r-,%2y?
int off = (m_size-m_index-1)%8; G0Iw-vf
mask <<=off; M*0]ai|;
return pc & mask; &s(^@OayE
} P1!qbFDv8
bit_iterator<Container>& operator++() )705V|v
{ Zj(AJ* r
m_index++; X;$+,&M"
return *this; \$K20)
} 5%"V[lDx@
bit_iterator<Container>& operator++(int) ;[ZEDF5H
{ j;zM{qu_
m_index++; /l3V3B7
return *this; GblA9F7
} hDDn,uzpd
bool operator==(bit_iterator<Container>& bitIt) dRYqr}!%n
{ Zpt\p7WQ
return m_index == bitIt.m_index; 3<Lx&p~%T
} 6XxvvMA97
bool operator!=(bit_iterator<Container>& bitIt) y
RqL9t
{ 10Q ]67
return !(*this == bitIt); _;"il%l=1
} #mxPw
protected: q])K,)
Container* m_container; }{Pp]*I<A
private: ./Xz}<($8
int m_size; ROI7eU
int m_index; 1C+13LE$U
}; }J}-//[A
%UrueMEO
用该迭代器可以将任意类型对象以二进制格式输出: g _9C*
double a = 10; v&\Q8!r_
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));