以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 %afz{a5
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 -IS$1
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 jdd3[
象当作char数组来处理。 A'suZpL
template<class Container> /X;!
F>
class bit_iterator : public std::iterator<bidirectional_iterator_tag, 7ZFd;-
void, void> +,UuJ6[n
{ / !aVv
public: GpXU&A'r
explicit bit_iterator(Container& c) : m_container(&c) zU";\);
{ :nS p
m_size = 8*sizeof(Container); 3j\Py'};
m_index = 0; !RwMUnp
} Dv}VmC""
explicit bit_iterator() : m_container(0) l} W">
yQ0
{ $d
Nmq
m_size = 8*sizeof(Container); }b+$S'`Bv
m_index = m_size; ggUw4w/e
} :.crES7<[X
bool operator* () c>+hY5?C
{ +T HBPEq
char mask = 1; +kx#"L:
char* pc = (char*)m_container; eKe[]/}e9
int i = (m_size-m_index-1)/8; 4okZ
int off = (m_size-m_index-1)%8; %";ap8J04F
mask <<=off; +<'>~lDg
return pc & mask; hy"=)n(
} `gdk,L]
bit_iterator<Container>& operator++() v,c;dlg_
{ }i52MI1-XP
m_index++; *R8P brN
return *this; +oiuulA
} Lv@'v4.({
bit_iterator<Container>& operator++(int) {;3a^K
{ ; Z2
m_index++; ;eC8|
Xz
return *this; ,EH^3ODD
} /U=?D(>x
bool operator==(bit_iterator<Container>& bitIt) */j[n$K>~`
{ +K48c,gt?
return m_index == bitIt.m_index; BP=<TRp.
} HjT -5>I7f
bool operator!=(bit_iterator<Container>& bitIt) iz2;xa*
{ 9n;6;K#
return !(*this == bitIt); v
K!vA-7
} \xX'SB#.l
protected: K}tC8D
Container* m_container; a.up&g_$
private: ese?;1r
int m_size; 1WAps#b.
int m_index; |fPR7-
}; )OZ
w%~Mg3|
用该迭代器可以将任意类型对象以二进制格式输出: -NUA
double a = 10; wcL|{rUXba
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));