以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 8cB=}XgYS
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 \6Xn]S
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 ";o~&8?)
象当作char数组来处理。 }tu4z+T2
template<class Container> t Z+0}d
class bit_iterator : public std::iterator<bidirectional_iterator_tag, mqubXS;J|P
void, void> R&gWqt/
{ ]LMiMj
public: i:;$oT
explicit bit_iterator(Container& c) : m_container(&c) Zi
ma^IL
{ 4bE42c=Ca7
m_size = 8*sizeof(Container); ]bf'
m_index = 0; 7bHE!#L`0
} =%xIjxYl
explicit bit_iterator() : m_container(0) ta@ISRK
{ wQ@Zwbx
m_size = 8*sizeof(Container); &:-GI)[o
m_index = m_size; S3nB:$_-;
} I.UjST
bool operator* () C"k2<IE
{ .x]'eq}
char mask = 1; mSy|&(l
char* pc = (char*)m_container; 1xq3RD
int i = (m_size-m_index-1)/8; av"Dljc
int off = (m_size-m_index-1)%8; C-_(13S
mask <<=off; F_K
return pc & mask; ShsJ_/C2
} }F~f&<GX6
bit_iterator<Container>& operator++() i[mC3ghM6,
{ !'+\]eA
m_index++; <##|311o
return *this; fi5YMYd1
} ux%&lff
bit_iterator<Container>& operator++(int) _xa}B,H
{ 2-QuT"Gkd
m_index++; {_rZRyr
return *this; 'W}~)+zK
} g9M')8a n
bool operator==(bit_iterator<Container>& bitIt)
b$PT_!d
{ C3]\$
return m_index == bitIt.m_index; K<D`(voL
} <yis
bool operator!=(bit_iterator<Container>& bitIt) ]6jHIk|
{ /j`i/Ha1
return !(*this == bitIt); N'htcC
} f34_?F<h
protected: 6s> sj7
Container* m_container; ~ W2:NQ>i
private: 9yO{JgKA
int m_size; qn5yD!1
int m_index; @?'t@P:4
};
~JAH-R
#8P#^v]H
用该迭代器可以将任意类型对象以二进制格式输出: ?ykVf O'
double a = 10; 2,rY\ Nu_
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));