以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 @%cJjZ5y
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 $ .Z2Rdlv(
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 +`Bn]e8O
象当作char数组来处理。 qK1V!a2
template<class Container> 2RXGY
class bit_iterator : public std::iterator<bidirectional_iterator_tag, !<6wrOMaO
void, void> hA\8&pI;
{ rqh,BkQ0t
public: YV940A-n
explicit bit_iterator(Container& c) : m_container(&c) 0j/81Y}p
{ S+>]8ZY
m_size = 8*sizeof(Container); B# H
m_index = 0; &lS0"`J=
} eB@i)w?@o
explicit bit_iterator() : m_container(0) `U1%d7[vY
{ aC$g(>xFt
m_size = 8*sizeof(Container); DVcu*UVw
m_index = m_size; CGe'z
} +l/j6)O`(m
bool operator* () ?-84_i
{ jRkq^}
char mask = 1; W=\dsdnu*
char* pc = (char*)m_container; .}<B*e=y
int i = (m_size-m_index-1)/8; .M{[J]H`t
int off = (m_size-m_index-1)%8; 1DcarF
mask <<=off; 9c7}-Go
return pc & mask; O]g+z$2o
} S7q&|nI
bit_iterator<Container>& operator++() @ty|HXW
{ (}}8DB
m_index++; kZ.3\
return *this; `k|nf9_
} 9|WWA%p
bit_iterator<Container>& operator++(int) ` ;=Se_
{ #"{8Z&Z
m_index++; piFQ7B
return *this; e,*[5xQ
} ;2|H6IN"
bool operator==(bit_iterator<Container>& bitIt) /_a *C.a6
{ L-R}O
8
return m_index == bitIt.m_index; -N(MEzAE
} PK4UdT
bool operator!=(bit_iterator<Container>& bitIt) kZ9pgdI
{ A,e^bM
return !(*this == bitIt); `x VA]GR4c
} L>b,}w
protected: dZgfls
Container* m_container; \IfgL$+
private: yMkd|1
int m_size; X8x>oV;8
int m_index; ex+AT;o
}; ]c2| m}I{:
k#) .E X
用该迭代器可以将任意类型对象以二进制格式输出: #+PbcL
double a = 10; o{LFXNcg[
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));