xiesx1985 发表于 2010-3-24 12:19:09

IAR编译环境下 将2个8Bit数据合成16bit数据出错~

unsigned char temp;
unsigned int test1;

temp = 0x01;
temp = 0x02;
temp = 0x03;


test1= *((unsigned int *)&temp); //把test和组合成整数;

//如果temp的地址是偶数地址,则test1的值为 0x0302

//但是,如果temp的地址是奇地址,则test1的值为 0x0201
   编译时,会提示A Word Access on odd address 0x44f.

有没有什么方法可以解决这个问题?

xiesx1985 发表于 2010-3-24 12:21:47

测试过了


#pragma pcak(1)

#pragma pack()
不能解决问题

huchunlei 发表于 2010-3-27 15:41:58

你用运算赋值的方法解决不行吗

unsigned char temp;
unsigned int test1;

temp = 0x01;
temp = 0x02;
temp = 0x03;

test1= (unsigned int)temp*0x100+temp;
或者这样:
test1= ((unsigned int)temp<<8)+temp;


另外还有个方法
union test
{
    unsigned int number;
    unsigned char temp;
}buffer;

buffer.temp = 0x01;
buffer.temp = 0x02;

那么,buffer.number 的值就是 0x0201 ,

这种方法多用于浮点数的拆分存储或者传输,但是用于数值组合的时候要注意一点,就是你的编译器对于整形数字是如何存储的,是高位字节在前还是低位字节在前,使用的时候要注意。

lryylryy 发表于 2010-3-27 19:10:55

楼上说的对,用运算的方法。

shengsg 发表于 2011-9-30 22:03:45

就是地址的问题
这是单片机在设计的时候决定的
没有什么好的办法更改的
只能按设计的来

brahen 发表于 2011-9-30 22:53:22

回复【2楼】huchunlei
你用运算赋值的方法解决不行吗
unsigned char temp;
unsigned int test1;
temp = 0x01;
temp = 0x02;
temp = 0x03;
test1= (unsigned int)temp*0x100+temp;
或者这样:
test1= ((unsigned int)temp&lt;&lt;8)+temp;
另外还有个方法
union test
{
    unsigned int number;
    unsigned char temp;
}buffer;
buffer.temp = 0x01;
buffer.temp = 0x02;
那么,buffer.number 的值就是 0x0201 ,
......
-----------------------------------------------------------------------

用结构体的方法确实巧妙。

Hello_World 发表于 2011-9-30 22:57:16

如同2楼的方法,我一直用结构体的方式,速度快。

make_studio 发表于 2011-10-12 18:25:44

unsigned char temp;
unsigned int test1;
unsigned char *p;

temp = 0x01;
temp = 0x02;
temp = 0x03;
   
p=(unsigned char*)&test1;
*p++=temp;
*p=temp;
页: [1]
查看完整版本: IAR编译环境下 将2个8Bit数据合成16bit数据出错~