- 论坛徽章:
- 0
|
本人定义了一个位段结构:
static struct packed_data {
unsigned char a:8;
unsigned char b:8;
unsigned char c:8;
unsigned char d:8;
} ;
目的为了对int类型的变量进行移位,然后将移位的结果拷贝到字符串内。
代码如下:
#include <stdio.h>
static struct packed_data {
unsigned char a:8;
unsigned char b:8;
unsigned char c:8;
unsigned char d:8;
} ;
extern void memcpy(char *,struct packed_data *,unsigned int);
main()
{
struct packed_data * pkdat;
unsigned int num,len;
char * buf0;
buf0=(char *)malloc(sizeof(char *));
pkdat=(struct packed_data * )malloc(sizeof(struct packed_data));
num=20202;
printf("sizof(pkdat)=[%d]\n",sizeof(pkdat));
printf("num=[%b]\n",num);
pkdat->a=(num>>0);
num>>=0;
pkdat->b=(num>> ;
num>>=8;
pkdat->c=(num>>16);
num>>=16;
pkdat->d=(num>>24);
printf("pkdat->a num2b() is [%b]\n",pkdat->a);
printf("pkdat->b num2b() is [%b]\n",pkdat->b);
printf("pkdat->c num2b() is [%b]\n",pkdat->c);
printf("pkdat->d num2b() is [%b]\n",pkdat->d);
memset(buf0,0,sizeof(buf0));
memcpy(buf0,pkdat,sizeof(pkdat));
printf("pkdat =[%b]\n",pkdat);
printf("buf0 =[%b]\n",buf0);
free(buf0);
free(pkdat);
}
此例中int变量为num=20202
我的本意是:
num[100111011101010]
右移后位段结构内容为
pkdat[11101010 01001110 00000000 00000000]
也就是4字节的num低位字节于高位字节顺序互换
并把结果保留到buf0
buf0[11101010 01001110 00000000 00000000]
但此代码运行结果如下:
sizof(pkdat)=[4]
num=[100111011101010]
pkdat->a num2b() is [11101010]
pkdat->b num2b() is [1001110]
pkdat->c num2b() is [0]
pkdat->d num2b() is [0]
pkdat =[10000000001100110100000]
buf0 =[10000000001100110011000]
 请高手给指点迷津3Q:)
[ 本帖最后由 dourt 于 2006-4-20 15:55 编辑 ] |
|