以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 L\%zNPLS
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 s`$YY_
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 0e,U&B<W
象当作char数组来处理。 b;2[E/JKB
template<class Container> iTu~Y<'m
class bit_iterator : public std::iterator<bidirectional_iterator_tag, :T9 P9<
void, void> d"nms\=p
{ UNOKK_
public: `z!6zo2d
explicit bit_iterator(Container& c) : m_container(&c) |!?lwBs4
{ tupAU$h?!
m_size = 8*sizeof(Container); CU+H`-+"J
m_index = 0; ObzFh?W
} ny'wS
explicit bit_iterator() : m_container(0) G^W'mV$xl
{ v~AD7k2{8
m_size = 8*sizeof(Container); 4R&e5!
m_index = m_size; tVr^1Y
} Evy_I+l
bool operator* () k )=Gyv<
{ mJYG k_ua
char mask = 1; }9*N EU)o
char* pc = (char*)m_container; xO0}A1t
Wd
int i = (m_size-m_index-1)/8; Id<O/C
int off = (m_size-m_index-1)%8; yLY$1#Sa
mask <<=off; Gl]z@ZXWIw
return pc & mask; .:(T}\]R
} szw|`S>o
bit_iterator<Container>& operator++() `Re{j{~s
{ 1> 'xmp+#
m_index++; K4vOy_wT
return *this; iw =~j
} .qfU^AHA
bit_iterator<Container>& operator++(int) Rz:1(^oA
{ z>A;|iL
m_index++; _(J4
return *this; \}EJtux q
} SpA-E/el
bool operator==(bit_iterator<Container>& bitIt) MnBHm!]&
{ xDO1gnH%
return m_index == bitIt.m_index; \L:+k `
} B.F~/PET
bool operator!=(bit_iterator<Container>& bitIt) hnTk)nq5#
{ bS&XlgnKi
return !(*this == bitIt); `+]e}*7$f
} |,lw$k93
protected: _BPp=(|
Container* m_container; -40s
private: |TQa=
int m_size; K0^Tg+U($p
int m_index; 5XF&yYWq
}; B"3uuk8
[ n2)6B\/
用该迭代器可以将任意类型对象以二进制格式输出: 8!|LJI
double a = 10; z:W|GDD1
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));