以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 mitHT :%r2
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 a#cCpE
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 1-8mFIK
象当作char数组来处理。 Y071Y:
template<class Container> N]>=p.#j
class bit_iterator : public std::iterator<bidirectional_iterator_tag, w$3,A$8
void, void> f',Op1o
{ pNG:0
public: 6dq(T_eG
explicit bit_iterator(Container& c) : m_container(&c) .[]r}[ lU
{ l5S aT,%
m_size = 8*sizeof(Container); F&!6jv
m_index = 0; .?8;q A
} wcrCEX=I>{
explicit bit_iterator() : m_container(0) -o^7r@6
{ / C:Y94B-z
m_size = 8*sizeof(Container); u
1>2v
m_index = m_size; wT6"U$cV
} pj\u9
L_
bool operator* () qzYwt]GNS
{
R5N%e%[
char mask = 1; CuaVb1r
char* pc = (char*)m_container; = 6j&4p
`
int i = (m_size-m_index-1)/8; R{C(K(5/
int off = (m_size-m_index-1)%8; `l\7+0W
mask <<=off; SL Ws*aq
return pc & mask; g#"zQv ON
} C8J[Up
bit_iterator<Container>& operator++() F|'>NL-=
{ $njUXSQ;
m_index++; S3q&rqarC%
return *this; 4`4kfiS$
} 8r*E-akuyr
bit_iterator<Container>& operator++(int) cXA
i k-
{ %^?fMeI|Y
m_index++; Y@;CF
return *this; &C`Gg<
} Gt\lFQ
bool operator==(bit_iterator<Container>& bitIt) wg9t)1k{e
{ *D'22TO[[!
return m_index == bitIt.m_index; :NhO2L
} G!Op~p@Jm
bool operator!=(bit_iterator<Container>& bitIt) cVXLKO
{ 0eT(J7[ <
return !(*this == bitIt); LoURC$lS
} !O\82d1P
protected: vDp8__^
Container* m_container; bg!/%[ {M
private: W,K;6TZhh
int m_size; Ansk,$
int m_index; \Z?9{J
}; R|6Cv3:
M92dZ1+6
用该迭代器可以将任意类型对象以二进制格式输出: @3>u@
double a = 10; f/ U`
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));