以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 Yj1|]i5b
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 xYCJO(&
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 Qv5fK
象当作char数组来处理。 E&
i (T2c
template<class Container> in/~' u
class bit_iterator : public std::iterator<bidirectional_iterator_tag, +/Y2\s
void, void> S'8+jY
{ :`zO%h
public: KD,3U/3
explicit bit_iterator(Container& c) : m_container(&c) #
:k=
{ P O 5Wi
m_size = 8*sizeof(Container); 6ICW>#fI`
m_index = 0; !#_2 ![
} 'mbLK#q
explicit bit_iterator() : m_container(0) o+&Om~W
{ T>'O[=UWh
m_size = 8*sizeof(Container); ,wes*
m_index = m_size; ^n0;Q$\
} \.}T_,I
bool operator* () XQ9W
y
{ wR@>U.XT@
char mask = 1; YB7n}r23
char* pc = (char*)m_container; %L* EB;nK
int i = (m_size-m_index-1)/8; RW+u5Y
int off = (m_size-m_index-1)%8; I51]+gEN
mask <<=off; :Q> e54]'&
return pc & mask; _*6]4\;
} ^J#*sn
bit_iterator<Container>& operator++() pT->qQ3;
{ 38p"lT
m_index++; 0 (wu
return *this; ~q}L13^k
} (g@\QdH`|
bit_iterator<Container>& operator++(int) mdEJ'];AH
{ *lvADW5e
m_index++; BYX c
'K
return *this; Zh;wQCDj
} }W8A1-UF
bool operator==(bit_iterator<Container>& bitIt) iW(LD1~7
{ rL1yq|]I
return m_index == bitIt.m_index; HvG %##
} '~&W'='b;
bool operator!=(bit_iterator<Container>& bitIt) @6yc^DAA
{ 6whPW
.
return !(*this == bitIt); } 7
o!
} 4F|79U #
protected: xj;:B( i
Container* m_container; cl4z%qv*
private: ih".y3
int m_size; ;,[0 bmL
int m_index; v#qd q!64
}; )1 T2u
O|,9EOrP
用该迭代器可以将任意类型对象以二进制格式输出: bh1$
A
double a = 10; W+#Q>^ Q>
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));