以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 ^*l
dsc
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 UhW{KIW
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 dE8f?L'
象当作char数组来处理。 75H!i$(*+
template<class Container> <y?+xZM]#|
class bit_iterator : public std::iterator<bidirectional_iterator_tag, **m8 HD
void, void> 2j4202
{ &PPnI(s^K
public: EC$F|T0f
explicit bit_iterator(Container& c) : m_container(&c) {Yxvb**
{ 8WDL.IO
m_size = 8*sizeof(Container); e*'bY;8lo
m_index = 0; b&!}SZ
} (+v':KH3_
explicit bit_iterator() : m_container(0) ^?fsJ
{ oU1N>,
m_size = 8*sizeof(Container); 8#$HKWUK
m_index = m_size; BD]J/o
} ,9G'1%z,
bool operator* () xytWE:=
{ H9jlp.F
char mask = 1; {G=> WAXo
char* pc = (char*)m_container; 5(#z)T
int i = (m_size-m_index-1)/8; 8-+# !]
int off = (m_size-m_index-1)%8; ]uhG&:
}
mask <<=off; $xW9))
return pc & mask; GjEV]hqR
} C4E}.``Hm
bit_iterator<Container>& operator++() S".|j$
{ 1sza\pR<
m_index++; ;PMPXN'z6
return *this; %62|dhl6
} ([$KXfAi]h
bit_iterator<Container>& operator++(int) )xc1Lsrr9
{ axnVAh|}S
m_index++; 9u=]D> kb
return *this; JT}"CuC
} x!I@cP#O
bool operator==(bit_iterator<Container>& bitIt) ){/n7*#Th%
{ t_I-6`8o]
return m_index == bitIt.m_index; nZj&Ma7R
} pD P*
3
bool operator!=(bit_iterator<Container>& bitIt) 6$PQ$
{ =^M Q 4
return !(*this == bitIt); b/.EA'/
} TQt[he$O
protected: d^?e*USh
Container* m_container; |oeg'T
private: UBv#z&@[
int m_size; H '5zl^8I
int m_index; |LIcq0Z
}; Dp*:oMATx0
uUaDesz~=
用该迭代器可以将任意类型对象以二进制格式输出: }6u}?>S
double a = 10; [EPRBK`=
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));