以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 LR!%iP
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 o2bmsnXQ
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 NS""][#
象当作char数组来处理。 0VNpd~G$
template<class Container> `QRXQ c
class bit_iterator : public std::iterator<bidirectional_iterator_tag, #@5VT*/7
void, void> ujN~l_4
{ v _:KqdmO]
public: ZR%$f-
explicit bit_iterator(Container& c) : m_container(&c) f*88k='\W
{ e6H}L:;
m_size = 8*sizeof(Container); t^>P,%$
m_index = 0; "#gS ?aS
} __s'/6u
explicit bit_iterator() : m_container(0) |uz\XK
{ @%*@Rar
m_size = 8*sizeof(Container); y`5
?
m_index = m_size; &OE-+z
} ^!i4d))
bool operator* () 6R8>w,
{ 7lAJ
0
char mask = 1; {oF;ZM'r
char* pc = (char*)m_container; 1{]S[\F]
int i = (m_size-m_index-1)/8; \CE+P5
int off = (m_size-m_index-1)%8; 0H.bRk/P+
mask <<=off; q4Bw5~n
return pc & mask; qmGHuQVe
} .@EzHe ^W
bit_iterator<Container>& operator++() 0S4Y3bac&
{ )c1Pj#|
m_index++; lKU{jWA
return *this; _A&
[rBm|
} $I/ !vV
bit_iterator<Container>& operator++(int) mA%}ijR6y
{ 7J`v#
m_index++; bG* l_
return *this; {~R?f$}""j
}
I![/bwObG
bool operator==(bit_iterator<Container>& bitIt) y!:vX6l
{ \*BRFUAc
return m_index == bitIt.m_index; 5 8L@:>"
} PY4a3dp
U
bool operator!=(bit_iterator<Container>& bitIt) ;{&4jcV*
{ <0hVDk~
return !(*this == bitIt); =h=-&DSA
} UHTxNK@}
protected: b "}ya/
Container* m_container; |0>rojMq
private: aO ?KRn
int m_size; Er8F_,M+
int m_index; 9-&@Y
}; dD'KP4Io@
%}-ogi/c
用该迭代器可以将任意类型对象以二进制格式输出: d!Ws-kzE
double a = 10; Mh3L(z]/E
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));