社区应用 最新帖子 精华区 社区服务 会员列表 统计排行 社区论坛任务 迷你宠物
  • 2979阅读
  • 0回复

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 e'9r"<>i  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 DN] v_u+}  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 )> a B  
象当作char数组来处理。 5&!c7$K0  
template<class Container> {XCf-{a]~  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, gm)@c2?.  
void, void> G }nO@  
{ t18$x "\4k  
public: 9Ul(GI(  
explicit bit_iterator(Container& c) : m_container(&c) yxWO [ Z  
{ 8|^CK|m6*  
m_size = 8*sizeof(Container); {*m?Kc7k  
m_index = 0; SPkn 3D6  
} ipE ]}0q  
explicit bit_iterator() : m_container(0) <wd]D@l7r  
{ +9;2xya2  
m_size = 8*sizeof(Container); fS&6  
m_index = m_size; X[yNFW}S2W  
} 6<76H  
bool operator* () ~NcQ1.  
{ @.C{OSH E  
char mask = 1; r' Z3  
char* pc = (char*)m_container; /RnTQ4   
int i   = (m_size-m_index-1)/8; #FxPj-3(ix  
int off   = (m_size-m_index-1)%8; jM)C4ii.-$  
mask <<=off; k@mVxnC  
return pc & mask; 4=8QZf0\  
} kFLB> j97  
bit_iterator<Container>& operator++() GX{XdJD  
{ Fr2N[\>s  
m_index++; K4ZolWbU  
return *this; eOT+'[3"  
} s%4M$ e  
bit_iterator<Container>& operator++(int) qQ]]~F  
{ ]; $] G-  
m_index++; 5*g]qJF  
return *this; 9LC&6Q5O&  
} i5}4(sV  
bool operator==(bit_iterator<Container>& bitIt) 5 `D-  
{  t+uE  
return m_index == bitIt.m_index; "2ru7Y"  
} ,M5}4E7L%s  
bool operator!=(bit_iterator<Container>& bitIt) r=.A'"Kf  
{ !^c@shLN4  
return !(*this == bitIt); dEa<g99[?  
} 2BXy<BM @  
protected: ~nLN`H d  
Container* m_container; bC!`@/  
private: OX]V) QHVZ  
int m_size; cZ8.TsI~  
int m_index; zmuMWT;  
}; xGk6n4Gg  
FDzqL;I  
用该迭代器可以将任意类型对象以二进制格式输出: O*6n$dUj3  
double a = 10; 1 T<+d5[C  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

您目前还是游客,请 登录注册
批量上传需要先选择文件,再选择上传
认证码:
验证问题:
10+5=?,请输入中文答案:十五