以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 sI^Xb@'09$
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 <;Zmjeb+#
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 BeoDKdAwY
象当作char数组来处理。 JB[~;nLlC
template<class Container> czRFMYE
class bit_iterator : public std::iterator<bidirectional_iterator_tag, hp-<2i^"!
void, void> Y^EcQzLw
{ i5Yb`Z[Y
public: l#Y,R 0
explicit bit_iterator(Container& c) : m_container(&c) xRLT=.ir
{ aH/
k Ua
m_size = 8*sizeof(Container);
k5.Lna
m_index = 0; 'op|B@y
} ;P%1j| 7
explicit bit_iterator() : m_container(0) p xa*'h"b^
{ y''z5['
m_size = 8*sizeof(Container); XBu"-(
m_index = m_size; &H/'rd0M
} D (?DW}Rqs
bool operator* () iN8zo:&Z
{ M {T-iW"
char mask = 1; xH"/1g
char* pc = (char*)m_container; "8jf81V*
int i = (m_size-m_index-1)/8; 7/@TF/V
int off = (m_size-m_index-1)%8; A1>OY^p3%
mask <<=off; O so#+
return pc & mask; *@=/qkaJaI
} 9c,'k#k
bit_iterator<Container>& operator++() N.{H,oO `
{ Jgd'1'FOs
m_index++; =Qj{T
return *this; +V046goX W
} 9} M?P
bit_iterator<Container>& operator++(int) Hp!-248 S
{ k],Q9
m_index++; =BAW[%1b
return *this; 0e ~JMUb
} c"V"zg22
bool operator==(bit_iterator<Container>& bitIt) EF}\brD1
{ r8rgY42
return m_index == bitIt.m_index; Y}|X|!0x
} vJc- 6EO
bool operator!=(bit_iterator<Container>& bitIt) CiLg]va
{ `1{ZqRFQ
return !(*this == bitIt); F]]]y5t
} /,&<6c-Q@W
protected: [<6^qla
Container* m_container; FX`>J6l:X
private: VfC <WVYiZ
int m_size; A:N|\Mv2b
int m_index; ][h%UrV
}; ]]9R mh=
$f=J2&D,Cz
用该迭代器可以将任意类型对象以二进制格式输出: {xB!EQ"
double a = 10; s.N/2F&*W
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));