以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 ]z+*?cc
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 PbbXi
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 |= tJ|
象当作char数组来处理。 iTj"lA
template<class Container> UY1JB^J$
class bit_iterator : public std::iterator<bidirectional_iterator_tag, YCir Oge
void, void> @47[vhE
{ )>-77\
public: J'I1,5(
explicit bit_iterator(Container& c) : m_container(&c) m(8jSGV
{ c Bg,k[,
m_size = 8*sizeof(Container); ^fFtI?.6jI
m_index = 0; s"pR+)jf1D
} |\i:LG1
explicit bit_iterator() : m_container(0) V"w`!
{ {E;2&d
m_size = 8*sizeof(Container); w> Tyk#7lw
m_index = m_size; IXbdS9,>F
} k&MlQ2'!<
bool operator* () ?BWHr(J
{ M(_^'3u
char mask = 1; (45NZBs
char* pc = (char*)m_container; <QYCo1_
int i = (m_size-m_index-1)/8; FE0qw1{qQ
int off = (m_size-m_index-1)%8; HiQoRk
mask <<=off; fBHkLRFH
return pc & mask; = 4BLc
} sN6 0o 7.
bit_iterator<Container>& operator++() 6V.awg,
{ MV
Hz$hyB
m_index++; l81&[
return *this; 2$o2.$i81
} &>&dhdTQ
bit_iterator<Container>& operator++(int) R59e&
{ g4~X#}:z$O
m_index++; VQ1?Db(_2
return *this; kHt!S9r
} &:;/]cwj
bool operator==(bit_iterator<Container>& bitIt) H arFo
{ nQ:ml
return m_index == bitIt.m_index; *,O
:>Z5I
} +O;OSZ
bool operator!=(bit_iterator<Container>& bitIt) TSc~$Q]
{ }}kS~
w-#
return !(*this == bitIt); a)I=U[
} C ffTv
protected: UgF) J
Container* m_container; %Nwyx;>9^K
private: )![f\!'PI
int m_size; n/KI"qa]9
int m_index; I
ybl;u
}; &