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.
有没有什么方法可以解决这个问题? 测试过了
用
#pragma pcak(1)
#pragma pack()
不能解决问题 你用运算赋值的方法解决不行吗
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 ,
这种方法多用于浮点数的拆分存储或者传输,但是用于数值组合的时候要注意一点,就是你的编译器对于整形数字是如何存储的,是高位字节在前还是低位字节在前,使用的时候要注意。 楼上说的对,用运算的方法。 就是地址的问题
这是单片机在设计的时候决定的
没有什么好的办法更改的
只能按设计的来 回复【2楼】huchunlei
你用运算赋值的方法解决不行吗
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 ,
......
-----------------------------------------------------------------------
用结构体的方法确实巧妙。 如同2楼的方法,我一直用结构体的方式,速度快。 unsigned char temp;
unsigned int test1;
unsigned char *p;
temp = 0x01;
temp = 0x02;
temp = 0x03;
p=(unsigned char*)&test1;
*p++=temp;
*p=temp;
页:
[1]