以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 = PqQJE}
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 5>t&)g
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 xB68RQe)
象当作char数组来处理。 >a%NC'~rc
template<class Container> N:)`+}
class bit_iterator : public std::iterator<bidirectional_iterator_tag, ]}<.Y[!S
void, void> !w[<?+%%n
{ `=^29LC#
public: $hPAp}
explicit bit_iterator(Container& c) : m_container(&c) qDM/
6xO
{ Wcz{": [
m_size = 8*sizeof(Container); oIt.Pc~;'#
m_index = 0; zG[fPD
}
doBfpQ2
explicit bit_iterator() : m_container(0) o$\{&:y
{ ?|%^'(U}
m_size = 8*sizeof(Container); T$06DS
m_index = m_size; H:`W\CP7_
} W([)b[-*
bool operator* () 0'TqW9P
{ +%>s\W+?]
char mask = 1; PkLRQ}
char* pc = (char*)m_container; &{7n
int i = (m_size-m_index-1)/8; ::dLOf8o
int off = (m_size-m_index-1)%8; `-D6:- ,w
mask <<=off; ?#qA>:2,
return pc & mask; V3$!`T}g4
} '# "Z$
bit_iterator<Container>& operator++() Fh?;,Z
{ $e+@9LNK
m_index++; "}\2zub9
return *this; *GfGyOS(
} Q# }} 1}Ja
bit_iterator<Container>& operator++(int) (i|`PA
{ -vGyEd7
m_index++; +AZ=nMgW
return *this; ,M>W) TSH
} 1#^[{XlAx
bool operator==(bit_iterator<Container>& bitIt) Qf414 oW
{ Nn
?B D4i
return m_index == bitIt.m_index; o2W pi
} +IuV8XT2(
bool operator!=(bit_iterator<Container>& bitIt) k!xi
(l<C
{ zek\AQN
return !(*this == bitIt); ,4NvD2Y
} ba%[!
protected: L:`|lc=^
Container* m_container; U#-&%|b$
private: ~1S7\e7{
int m_size; A~ '2ki5$g
int m_index; `kwyF27v]
}; *na7/ysT<
mppBc-#EYr
用该迭代器可以将任意类型对象以二进制格式输出: Ufv{6"sH
double a = 10; ";`ddN3
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));