以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 b5Pn|5AVj
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 P `"7m-
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 Sg-xm+iSDt
象当作char数组来处理。 ja/[PHq"
template<class Container> +b+sQ<w?.
class bit_iterator : public std::iterator<bidirectional_iterator_tag, &}O!l'
void, void> &iZYBa
{ +QX>:z
public: o2
explicit bit_iterator(Container& c) : m_container(&c) #A;Z4jK
{ kg@h R}
m_size = 8*sizeof(Container); ~\ f^L?m
m_index = 0; aTsfl
} b U NYTF{
explicit bit_iterator() : m_container(0) DOe KW
{ 1!3kAcBP
m_size = 8*sizeof(Container); 4Z}{hc\J
m_index = m_size; ;Oy>-Ij5P
} 7h1gU
bool operator* () ]'(7T#
{ s~
A8/YoU}
char mask = 1; <q\)
o_tH
char* pc = (char*)m_container; Ib!rf:
int i = (m_size-m_index-1)/8; 31& .Lnq
int off = (m_size-m_index-1)%8; I})t
mask <<=off; yipD5,TC
return pc & mask; r%d11[z
} ^z^e*<{WEl
bit_iterator<Container>& operator++() E]U0CwFtr
{ /T[ICd2J
m_index++; Hs=N0Sk]j
return *this; RH]>>tJ^e
} b6&NzUt34V
bit_iterator<Container>& operator++(int) aG_ON0g
{ pm~;:#z7
m_index++; $?AA"Nz
return *this; #J724`
} ?VQLY=?
bool operator==(bit_iterator<Container>& bitIt) '%C.([
{ 8G&+
return m_index == bitIt.m_index; f\|?_k]
} Fx5d@WNa>
bool operator!=(bit_iterator<Container>& bitIt) D1 ~x
{ F*t_lN5{
return !(*this == bitIt); ([b!$o<v
} Qk.Q9@3W
protected: 86fK=G:>
Container* m_container;
/1~|jmi(
private: -MU.Hu
int m_size; Yc`j
int m_index; F(9
Y/UXH
}; V<ApHb
ds;cfj[
用该迭代器可以将任意类型对象以二进制格式输出: e ]o'i;I
double a = 10; Q &7)vs
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));