以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 \Vl)q>K_h
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 %QFeQ(b/(
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 ##/ l
象当作char数组来处理。 SI:Iv:>
template<class Container> x)-n[Fu
class bit_iterator : public std::iterator<bidirectional_iterator_tag, 8QN/D\uq
void, void> dW#?{n-H<
{ =[IKwmCX
public: -'RD%_
explicit bit_iterator(Container& c) : m_container(&c) \bv JZ_
{ ]h}O&K/
m_size = 8*sizeof(Container); 9[Xe|5?c
m_index = 0; oZ!+._9
} drh,=M\F
explicit bit_iterator() : m_container(0) zN7Ou .
{ gutf[Ksu
m_size = 8*sizeof(Container); 'Ad |*~
m_index = m_size; %p
tw=Ju
} [G7S
bool operator* () XA-,
{ 9DaoMOPEI
char mask = 1; hXQo>t-$
char* pc = (char*)m_container; |k=5`WG
int i = (m_size-m_index-1)/8; 9RJFj?^"
int off = (m_size-m_index-1)%8; okLheF
mask <<=off; 89a`WV@}
return pc & mask; l8RKwECdPn
} I0(nRu<
bit_iterator<Container>& operator++() VpWpC&
{ V; 1i/{
m_index++; Cp^%;(@
return *this; iK9#{1BpML
} y+P$}Nru
bit_iterator<Container>& operator++(int) +3o
4KB}
{ !l~3K(&4
m_index++; B}npom\tC
return *this; +M.!_2t$2
} -SKcS#IF
bool operator==(bit_iterator<Container>& bitIt) -|`E'b81
{ vff`Xh>k(
return m_index == bitIt.m_index; m,#Us
} Y$N D
bool operator!=(bit_iterator<Container>& bitIt)
nIv/B/>pZ
{ wPH1g*U
return !(*this == bitIt); 5c-'m?k
} 4Q^i"jT
protected: <77v8=as5
Container* m_container; 1zc-$B`t
private: m'5rzZP
int m_size; <R8!fc{`
int m_index; .$s=E8fW
}; 6x"|,,&MD0
$jL+15^N0+
用该迭代器可以将任意类型对象以二进制格式输出: Tg/rV5@ka
double a = 10; 07A2@dx
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));