以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 Yg,lJ!q
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 s]8J+8
<uO
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 qVe6RpS
象当作char数组来处理。 4NR5?s
template<class Container> 5a|m}2IX
class bit_iterator : public std::iterator<bidirectional_iterator_tag, 8lGgp&ey
void, void> (Dh;=xG
{ S!!\!w>N
public: W
(c\$2`
explicit bit_iterator(Container& c) : m_container(&c) ts\>_/
{ S,9WMti4x
m_size = 8*sizeof(Container); `&[:!U2]F
m_index = 0; YJvT
p~
} -&D6w9w
explicit bit_iterator() : m_container(0) f#Cdx"
{ <\>ak7m
m_size = 8*sizeof(Container); SVWSO
m_index = m_size; WJ4UJdf'
} ?!j/wV_H
bool operator* ()
x Bw.M{
{ )bU")
char mask = 1; +pViHOJu&V
char* pc = (char*)m_container; zp-~'kIJ
int i = (m_size-m_index-1)/8; t}+c/ C%b=
int off = (m_size-m_index-1)%8; M &EJFpc*
mask <<=off; 7:q-NzE\6
return pc & mask; Or)c*.|\
} n]c,0N
bit_iterator<Container>& operator++() Wc;D{p?Lb
{ 9,> Y
m_index++; 2co{9LM
return *this; Y '*h_K
} (wF$"c3'{
bit_iterator<Container>& operator++(int) U9sub6w 6
{ 7{F9b0zwk
m_index++; 7#.PMyK9
return *this; kGiw?~t=%
} !Ocg
bool operator==(bit_iterator<Container>& bitIt) tU/NwA"
{ a(T4WDl^
return m_index == bitIt.m_index; <G?85*Nv_
} HwMsP$`q
bool operator!=(bit_iterator<Container>& bitIt) }4]x"DfIg
{ 'wV26Dm
return !(*this == bitIt); V="f)'S$
} *LdH/C.LIf
protected: QO1Gq9
Container* m_container; pytfsVM
private: TFNU+
int m_size; y/VmjsN}
int m_index; 7$P(1D4
}; M|=$~@9#X
Nh/ArugP5P
用该迭代器可以将任意类型对象以二进制格式输出: 9],"AjD
double a = 10; zR_l^NK
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));