以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 ?yp0$r/
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 ;+
G9-
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 B
s,as
象当作char数组来处理。 J/t!-!
template<class Container> "IG+V:{ou
class bit_iterator : public std::iterator<bidirectional_iterator_tag, nX._EC
void, void> Z v4<b
{ _9NVE|c;
public: R uLvG+
explicit bit_iterator(Container& c) : m_container(&c) J='W+=N
{ 0N{+y}/G
m_size = 8*sizeof(Container); Ib1e#M3
m_index = 0; h~w4, T
} W
(`c
explicit bit_iterator() : m_container(0) azo0{`S?
{ *zy'#`>
m_size = 8*sizeof(Container); RlsVC_H\
m_index = m_size; 1kmQX+f
} O%-h&C3
bool operator* () Ziz=]D_
{ y? "@v.
char mask = 1; (S oo<.9~
char* pc = (char*)m_container; H0a-(
int i = (m_size-m_index-1)/8; =Y9\DeIZ
int off = (m_size-m_index-1)%8; ANMYX18M
mask <<=off; 0KAj]5nvb
return pc & mask; ^mg*;8eGa
} [T`}yb@
bit_iterator<Container>& operator++() 3sFeP&
{ nLy#|C
m_index++; "!H@k%eAM|
return *this; 5lTD]d
} Q.k
:\m*h
bit_iterator<Container>& operator++(int) /s
c.C
{ %9o+zg? RJ
m_index++; M^6$
MMx
return *this; 1zjaR4Tf
} Ax!Gu$K2o
bool operator==(bit_iterator<Container>& bitIt) kZVm1W1
{ iq6a|XGi
return m_index == bitIt.m_index; xMI+5b8
} 0Q~@F3N-\>
bool operator!=(bit_iterator<Container>& bitIt) O"*`'D|hK
{ t};~H\:
return !(*this == bitIt); TJaeQqob
} sS!w}o2X
protected: $
[7 Vgs
Container* m_container; k=/eM$":
private: @u)
'yS
int m_size; B8m_'!;;
int m_index; H{V)g
}; nxaT.uFd1
h1+hds+
用该迭代器可以将任意类型对象以二进制格式输出: (ZP87Gz
double a = 10; ->E=&X
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));