以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 vFz#A/1
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 h@^d
Vg
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对
w~3~:w$
象当作char数组来处理。 JKXb$
template<class Container> Y`U[Y Hx
class bit_iterator : public std::iterator<bidirectional_iterator_tag, Xf"B\%,(`
void, void> THOXs;
k0
{ ^L,Uz:[J
public: 0m,3''Q5lO
explicit bit_iterator(Container& c) : m_container(&c) vmY 88Kx&S
{ 0sQt+_Dl%L
m_size = 8*sizeof(Container); UhI T!x
m_index = 0;
@_ZE_n
} , sOdc!![
explicit bit_iterator() : m_container(0) ;b-d2R
{ 0-=PP@W
m_size = 8*sizeof(Container); 2i4&*&A
m_index = m_size; ;%wY fq~P
} .$rt>u,8<
bool operator* () \i2S'AblYq
{ =!~6RwwwY
char mask = 1; odm!}stus
char* pc = (char*)m_container; 8+?|4'\`
int i = (m_size-m_index-1)/8; {SQ#n@Q&$
int off = (m_size-m_index-1)%8; w]%|^:
mask <<=off; /'ukeK+'
return pc & mask; Jtv~n
} H2cY},
bit_iterator<Container>& operator++() q_R^Q>ZIe
{ 8iIz!l%O
m_index++; k>'c4ay290
return *this; 3jJd)C R
} ` 465
H
bit_iterator<Container>& operator++(int) 2JMMNpya
{ -Y{=bZS u
m_index++; pSPVY2qKX
return *this; hd'JXKMy
} Za>0&Fnf
bool operator==(bit_iterator<Container>& bitIt) T\
cJn>kCn
{ -!ARVf *
return m_index == bitIt.m_index; Q&@~<!t
} PlX6,3F
bool operator!=(bit_iterator<Container>& bitIt) Wifr%&t{J
{
g%.;ZlK
return !(*this == bitIt); egd%,`
} hE9UWa.Q>
protected: QrX 5Kwq
Container* m_container; *=KX0%3
private: dB=aq34l
int m_size; qGYru1
int m_index; Y~fa=R{W
}; ,t!K? Y
in[yrqFb7t
用该迭代器可以将任意类型对象以二进制格式输出: x3QQ`w-
double a = 10; vz*'1ugaA
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));