关于一个位运算的算法求助

xysome 2003-07-19 10:29:54
现在有一个位运算的问题请教大家:
从一个文件中读取二进制数据,比如,读取了10字节,存入一个字符数组中;现在,想取出从第3个字节第2位到第5个字节的第7位,并存入一个变量中。
那么请问:
1、如何实现这个算法?
2、这个变量应该声明为什么类型?
...全文
54 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
zteliubin 2003-07-19
  • 打赏
  • 举报
回复
re: Polarislee(北极星)

呵呵,没用过bitset,c语言是没有的,我还是喜欢直接操作
也就两3行代码而已嘛!
北极猩猩 2003-07-19
  • 打赏
  • 举报
回复
用bitset岂不是更方便
zteliubin 2003-07-19
  • 打赏
  • 举报
回复
我已经验证了,没有问题,呵呵,给分吧!

main()
{ unsigned char a[10] = { 0x10,0xf0,0x0f,0x0a,0xf0,0x00,0x00,0x00,0x00,0x00};
int n;
memcpy(&n,&a[2],3); //拷贝3,4,5字节
n &= 0x007fffff;//去掉第5字节的8字节
n >>= 1;//去掉第3字节的第1个bit,共保留22bit
unsigned char *p=&a[2];
for(int i=0;i<4;i++) printf("%x ",*p++);
printf("\nn=0x%x\n",n);
p=(unsigned char*)&n;
for(i=0;i<4;i++) printf("%x ",*p++);
printf("\n");
}

运行结果如下:
f a f0 0
n=0x380507
7 5 38 0

说明一下,这是基于x86体系的结果!
zteliubin 2003-07-19
  • 打赏
  • 举报
回复
不好意思,有错误!
我的实现是把第3字节作为int低子介,第5字节作为int高字节,
这样改一下就可以了://假设你说的数字序号从1开始而不是从0开始
char a[10];

int n;
memcpy(&n,&a[2],3); //拷贝3,4,5字节
n &= 0x007fffff;//去掉第5字节的8字节
n>>1;//去掉第3字节的第1个bit,共保留22bit


zteliubin 2003-07-19
  • 打赏
  • 举报
回复
如果包含第2个子节和第7个字节的话,共30bit,因此用int就可以;
实现,要视你的要求,是哪个作为高位,哪个作为低位

一种实现方法:
char a[10];

int n;
memcpy(&n,&a[2],4);
n>>2;

晨星 2003-07-19
  • 打赏
  • 举报
回复
可以保存到bitset对象中。
bigiron 2003-07-19
  • 打赏
  • 举报
回复
不好意思,题目没有看清楚
bigiron 2003-07-19
  • 打赏
  • 举报
回复
这样比较好:

typedef struct __bit{
unsigned char b0:1;
unsigned char b1:1;
unsigned char b2:1;
unsigned char b3:1;
unsigned char b4:1;
unsigned char b5:1;
unsigned char b6:1;
unsigned char b7:1;
} BITS;

typedef union __Array{
unsigned char abyte;
BITS bits;
} theArray;

theArray myarray[10];
bigiron 2003-07-19
  • 打赏
  • 举报
回复
试试数组的类型是以下这个union看看:

union __a{
unsigned char abyte;
struct __bit{
unsigned char b0:1;
unsigned char b1:1;
unsigned char b2:1;
unsigned char b3:1;
unsigned char b4:1;
unsigned char b5:1;
unsigned char b6:1;
unsigned char b7:1;
}bit;
}a;
zteliubin 2003-07-19
  • 打赏
  • 举报
回复
那就不是一个普通类型能够表示的,如果一定要的话,那就
定义一个数组来存放:

#define ARRAY_SIZE 10
unsigned char a[ARRAY_SIZE] = { 0x10,0xf0,0x0f,0x0a,0xf0,0x00,0x00,0x00,0x00,0x00};
unsigned char b[ARRAY_SIZE];

for(int i=0;i<ARRAY_SIZE-1;i++)
b[i] = a[i]>>1 | a[i+1]<<7; //每个字节等于本字节的高7个bit与下一个字节0bit拼接
b[i]=a[i] & 0x7f; //处理第10个字节
bugbugbug 2003-07-19
  • 打赏
  • 举报
回复
那只能自定义一个类来处理了。

不过我对你这样作的目的感到有点奇怪!
xysome 2003-07-19
  • 打赏
  • 举报
回复
谢谢!分一定多多的给,呵呵。
但是,最后请教一下:如果我想取出其中从第1个字节第2位到第10个字节的第7位,用int或者long什么的好像都不足以表示了;这时候应该如何处理?

69,368

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧