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

以二进制格式输出对象

级别: 终身会员
发帖
3743
铜板
8
人品值
493
贡献值
9
交易币
0
好评度
3746
信誉值
0
金币
0
所在楼道
以二进制格式输出对象基本思路是直接将对象的内存数值以二进制的格式输出,但是如何获取对象内存的二进制结构 4cs`R+]o  
是关键。解决方法是通过位操作找出对象内存的每一个bit的值。并把该方法封装成一个迭代器。 kR'!;}s  
要注意的问题是位操作符只能对整数类型进行操作,为了对所有类型的对象都有效,必须将对 C YnBZ  
象当作char数组来处理。 r{Xh]U&>k  
template<class Container> /LJ?JwAvg5  
class bit_iterator : public std::iterator<bidirectional_iterator_tag, bk"` hq  
void, void> -BB5bsjA  
{ JSO>rpO  
public: dmf~w_(7  
explicit bit_iterator(Container& c) : m_container(&c) N=|w]t0*yc  
{ siOeR@> X  
m_size = 8*sizeof(Container); Q%@l`V)Rs  
m_index = 0; 8 v&5)0u  
} 0xH$!?{b  
explicit bit_iterator() : m_container(0) +DVU"d  
{  #p\sw  
m_size = 8*sizeof(Container); Z\NC+{7k]  
m_index = m_size; <m9IZI Y<  
} PN<Y&/fB  
bool operator* () o%CBSm]  
{ 4(o0I~hpB?  
char mask = 1; X8Gw8^t  
char* pc = (char*)m_container; A4'v Jk  
int i   = (m_size-m_index-1)/8; eZf-i1lJ  
int off   = (m_size-m_index-1)%8; z07!i@ue~  
mask <<=off; RN!oflb  
return pc & mask; .w&{2,a3  
} /eZA AH  
bit_iterator<Container>& operator++() N7Dm,Q]  
{ '9i:b]Hru  
m_index++; C[&L h_F\  
return *this; W"z!sf5U  
} #{<Jm?sU  
bit_iterator<Container>& operator++(int) 2,dG Rf  
{ [7L1y) I(  
m_index++; ?EKYKLwr  
return *this; pNE!waR>  
} v!40>[?|p  
bool operator==(bit_iterator<Container>& bitIt) S[*e K Z  
{ .lRO; D  
return m_index == bitIt.m_index; y8 `H*s@  
} *bwLi h!}H  
bool operator!=(bit_iterator<Container>& bitIt) !sfUrUu  
{ b8T'DY;~  
return !(*this == bitIt); OHe<U8iu%  
} 2D&tDX<  
protected: KWU#Swa`  
Container* m_container; 6\'v_A O  
private: 5P+3D{  
int m_size; V .$<  
int m_index; >WG$!o+R  
}; !*EHr09N7  
# |2w^Kn  
用该迭代器可以将任意类型对象以二进制格式输出: +-HaYB|p  
double a = 10; `N2zeFG  
copy(bit_iterator<double>(a), bit_iterator<double> (), ostream_iterator<bool>(cout, ""));
评价一下你浏览此帖子的感受

精彩

感动

搞笑

开心

愤怒

无聊

灌水
描述
快速回复

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