以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 >WG$!o +R
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 ~vG~Z*F
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 S1zV.]
象当作char数组来处理。 !%]]lxi
template<class Container> MNkysB(
class bit_iterator : public std::iterator<bidirectional_iterator_tag, 2 }+V3/
void, void> m<r.sq&;
{ oDA1#-
public: RM QlciG
explicit bit_iterator(Container& c) : m_container(&c) [ bE9Y;
{ >|H=25N>;
m_size = 8*sizeof(Container); zn@tLLX
m_index = 0; F5&4x"c
} L
+-B,466
explicit bit_iterator() : m_container(0) { 5h6nYu
{ Zj!S('hSY
m_size = 8*sizeof(Container); &eyFApM[Z
m_index = m_size; K*p^Gs,
} mtmtOG_/=
bool operator* () =3""D{l
{ #^#N%_8
char mask = 1; eEupqOF*:W
char* pc = (char*)m_container; g9p#v$V
int i = (m_size-m_index-1)/8; \ tU91VIj
int off = (m_size-m_index-1)%8; O:#t>
;
mask <<=off; hA)3Ah*
return pc & mask; Xg#Dbf4
} e6#^4Y/+`
bit_iterator<Container>& operator++() .2Gn)dZU
{ d\xh>o
m_index++; -KbT[]
return *this; Cv~ t~
} #%B1,.A
bit_iterator<Container>& operator++(int) JFl@{6c
{ h dPKeqg7
m_index++; O*!+D-
return *this; Q]7r?nEEhW
} A5B 5pJ
bool operator==(bit_iterator<Container>& bitIt)
M9 _h0
{
X1y1
return m_index == bitIt.m_index; W<v?D6dFq
} 0M-Zp[w\-
bool operator!=(bit_iterator<Container>& bitIt) ; #e-pkV
{ c:hOQZ
return !(*this == bitIt); 3fn6W)v?
} lOcvRF
protected: /dBQ*f5
Container* m_container; Y
KeOH
private: i%v^Zg&FU
int m_size; R&=Y7MfZ
int m_index; 44($a9oa2
}; N2xgyKy~
7@|(z:uw
用该迭代器可以将任意类型对象以二进制格式输出: 6^}GXfJAc
double a = 10; e,|"9OK
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));