以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 q1L>nvE
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 g||
q
3
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 cE`qfz
象当作char数组来处理。 %7`eT^
template<class Container> {na>)qzKP
class bit_iterator : public std::iterator<bidirectional_iterator_tag, x2&5zp
void, void> 9eHqOmz
{ 4@\$k+v
public: MtPdpm6\
explicit bit_iterator(Container& c) : m_container(&c) lx5.50mI
{ 7_Te-i
m_size = 8*sizeof(Container); ndDF(qHr
m_index = 0; "AXgT[ O
} DAf@-~c
explicit bit_iterator() : m_container(0) fW=<bf
{ >)NS U
m_size = 8*sizeof(Container); 'L7u`
m_index = m_size; @N<h`vDa
} GY@:[u.&
bool operator* () ;AVIt!(L~V
{ LU8[$.P
char mask = 1; ( 1
char* pc = (char*)m_container; 5c}loOq
int i = (m_size-m_index-1)/8; o-&0_Zq_
int off = (m_size-m_index-1)%8; W+8s>
mask <<=off; QX}JQ<8
return pc & mask; p`\>GWuT!
} _}JMBIq$
bit_iterator<Container>& operator++() TYR \K
{ wBw(T1VN
m_index++; Iy;"ht6
return *this; 4Ng:7C2
} jHE^d<=O^
bit_iterator<Container>& operator++(int) z#`Qfvu6Hi
{ B>cT<B
m_index++; l+&DBw[
return *this; Zw{?^6;cS
} GNuIcy
bool operator==(bit_iterator<Container>& bitIt) ~;]zEq-hG
{ TUwX4X6m
return m_index == bitIt.m_index; N8kNi4$mp=
} V'dw=W17V
bool operator!=(bit_iterator<Container>& bitIt) 2/A*\
{ 9* 3;v;F
return !(*this == bitIt); =~W=}
} Vh=U/{Rp1
protected: -~(d_
Container* m_container; 8BZ&-j{
private: <2<2[F5Q%
int m_size; T+RC#&>
int m_index; [r Nd7-j <
}; t~4Cf])
aY.cx1"
用该迭代器可以将任意类型对象以二进制格式输出: w8$>
2
double a = 10; `bV&n!Y_
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));