c – 迭代一个位域的成员
发布时间:2020-12-16 10:28:19 所属栏目:百科 来源:网络整理
导读:我们有这个例子: struct X { int e0 : 6; int e1 : 6; int e2 : 6; ... int e10 : 6;};struct X c; 如何“自动”访问成员,类似于: c.e {0-10}? 如果我想读c.e0,那么c.e1 … 如果我的结构有1000个元素,我不认为我应该编写这么多代码,对吧? 你能帮我解决一
我们有这个例子:
struct X { int e0 : 6; int e1 : 6; int e2 : 6; ... int e10 : 6; }; struct X c; 如何“自动”访问成员,类似于: 你能帮我解决一个问题吗? 非常感谢你 ! 解决方法
正如其他人所说,你不能用比特字段做你想要的.看起来你想要存储大量的6位整数,以最大的空间效率.我不会争论这是不是一个好主意.相反,我将使用C功能进行封装(未经测试),呈现一种老式的C方式.这个想法是4个6位整数需要24位或3个字符.
// In each group of 3 chars store 4 6 bit ints const int nbr_elements = 1000; struct X { // 1,2,3 or 4 elements require 3 chars,5,6,7,8 require 6 chars etc. char[ 3*((nbr_elements-1)/4) + 3 ] storage; int get( int idx ); }; int X::get( int idx ) { int dat; int offset = 3*(idx/4); // eg idx=0,1,3 -> 0 idx=4,7 -> 3 etc. char a = storage[offset++]; char b = storage[offset++]; char c = storage[offset]; switch( idx%4) // bits lie like this; 00000011:11112222:22333333 { case 0: dat = (a>>2)&0x3f; break; case 1: dat = ((a<<4)&0x30) + ((b>>4)&0x0f); break; case 2: dat = ((b<<2)&0x3c) + ((c>>6)&0x03); break; case 3: dat = c&0x3f; break; } return dat; } 我将伴侣put()函数作为练习. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |