以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 Z~
(QV0}
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 0n%`Xb0q
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 +a{>jzR
象当作char数组来处理。 3zkq'lZ
template<class Container> d4U_Wu&
class bit_iterator : public std::iterator<bidirectional_iterator_tag, -#@;-2w
void, void> {Ffr l(*
{ bk2vce&
public: \_oHuw
explicit bit_iterator(Container& c) : m_container(&c) YR>x h2< 9
{ fQ@["b
m_size = 8*sizeof(Container); o5d)v)Rx=
m_index = 0; 9(Z)c
} QGa"HG5NF
explicit bit_iterator() : m_container(0) bk|>a=o3
{ I[/u5V_b'
m_size = 8*sizeof(Container); B7
T+a
m_index = m_size; W# $rC<Jh]
} asb")NfIm
bool operator* () "Y6f.rB
{ V_:/#G]jeG
char mask = 1; W NCd k$
char* pc = (char*)m_container; L=>N#QR7
int i = (m_size-m_index-1)/8; *Co+UJjT
int off = (m_size-m_index-1)%8; o_S8fHqjt
mask <<=off; b^1!_1c
return pc & mask; #F
kdcY
} y}8j_r
bit_iterator<Container>& operator++() cVU[>gkg_
{ d+kIof,
m_index++; d] {^
return *this; N6eY-`4y
} 2gi`^%#k]
bit_iterator<Container>& operator++(int) }6\p7n
{ iqpy5
m_index++; j`bOJTBE
return *this; V@F~Cx
} SExd-=G
bool operator==(bit_iterator<Container>& bitIt) nX~sVG{Q
{ Y0DBkg
return m_index == bitIt.m_index; DY%E&Vd:h
} '<O&
:
bool operator!=(bit_iterator<Container>& bitIt) -7u4f y{T
{ *ZRQ4i[+
return !(*this == bitIt); +'l@t
bP
} K.k=\N
protected: ^K8Ey#T
Container* m_container; 3;&N3:,X
private: p AD@oPC
int m_size; crUXpD
int m_index; VHy$\5oYg
}; w%htY.-
r'j*f"uAm
用该迭代器可以将任意类型对象以二进制格式输出: /D
eU`rj
double a = 10; $?7}4u,
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));