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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 [;pL15-}4  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 v 8B4%1NE  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 yfZYGhPN(  
象当作char数组来处理。 $2>"2*,04  
template<class Container>  _W  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, oqa8v6yG'  
void, void> 0]Qk*u<  
{ y1bo28  
public: V|vXxWm/  
explicit bit_iterator(Container& c) : m_container(&c) ly::?  
{ #:xv]qb`k  
m_size = 8*sizeof(Container); ^D?{[LBc  
m_index = 0; %fIYWu`X  
} eZ|_wB'r  
explicit bit_iterator() : m_container(0) ,FK.8c6g  
{ +QA|]Y~!  
m_size = 8*sizeof(Container); V$g!#V  
m_index = m_size; >Q2kXwN  
} )S^[b2P]y_  
bool operator* () [{.9#cQ "  
{ .s%dP.P:i1  
char mask = 1; `4-m$ab  
char* pc = (char*)m_container; fbW<c`LH  
int i   = (m_size-m_index-1)/8; M~ g{}_ 0Z  
int off   = (m_size-m_index-1)%8; /kV5~i<1S  
mask <<=off; er.;qV'Wz6  
return pc & mask; |& _(I  
} 8 Y))/]R  
bit_iterator<Container>& operator++() n um2HtU&%  
{ I.- I4F)D  
m_index++; w"q^8"j!  
return *this; A2''v3-h8  
} MS& 'Nj  
bit_iterator<Container>& operator++(int) O5ZR{f&  
{ ' BY|7j~  
m_index++; Tua#~.3}J  
return *this; }Io5&ww:U  
} Xj$'i/=-+c  
bool operator==(bit_iterator<Container>& bitIt) R_Uy.0=4  
{ Sz>Lbs  
return m_index == bitIt.m_index; Hli22~7T:  
} Svm'ds7>  
bool operator!=(bit_iterator<Container>& bitIt) 0A F}wz>  
{ -_irkpdC[  
return !(*this == bitIt); lbC9^~T+  
} /|8/C40aY  
protected: <X ([VZ  
Container* m_container; z0?IQzR^T  
private: zE?@_p1gei  
int m_size; 9lB$i2G>Zw  
int m_index; ;]_h")4"c  
}; U4h5K}j4  
%(>,eee_  
用该迭代器可以将任意类型对象以二进制格式输出: z)%]# QO  
double a = 10; pQk@ +r  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

您目前还是游客,请 登录 或 注册
如果您提交过一次失败了,可以用”恢复数据”来恢复帖子内容
认证码:
验证问题:
10+5=?,请输入中文答案:十五