Accessing individual bytes in a long int

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 
已解决

Accessing individual bytes in a long int

跳至解决方案
1,054 次查看
stevec
Contributor III

I have to assemble a 4 byte int (long int) from four individual bytes that I am reading from a Flash memory device. Using lots of shifts seems a bit clumsy. Is there a method using a pointer to the long int to access the individual bytes? It seems a bit of a trivial question I know but I am a bit rusty with pointers. I'm using  a 9S08QE8.

 

Steve

标签 (1)
1 解答
810 次查看
bigmac
Specialist III

Hello,

One simple method is to create a union between the 32-bit value and a 4-element array.  For example,

typedef union {

  unsigned long lword;

  unsigned char a[4];

} TYPE_32BIT;


TYPE_32BIT val;

Access to 8-bit elements can be achieved with val.a[i], and access to the 32-bit quantity with val.lword.

Regards,

Mac

在原帖中查看解决方案

0 项奖励
5 回复数
810 次查看
Monica
Senior Contributor III

Hello Steve!

Did you get to try that out? How did it go?

Keep us posted! :smileywink:

Best regards,

Monica.

0 项奖励
810 次查看
stevec
Contributor III

Monica,

I had a chance to try the union solution that bigmac suggested. Works a treat and a much more elegant solution than lots of shifts, and a lot quicker. So thanks Mac. I hadn't got to the chapter on Unions yet. That's a lot further on in the book!! So it must be complicated, right? I hadn't realised it was so simple. Something new learnt.

Steve

810 次查看
Monica
Senior Contributor III

Yes, our dear friend bigmac ROCKS :smileygrin:

And so do you, keep the developing mood on!

Best regards,

Monica.

0 项奖励
810 次查看
stevec
Contributor III

Hi Monica,

No I haven't had a chance yet. I had figured out a less efficient way round it so it works after a fashion (although I have not looked at the assembler to check). I am also not familiar with using unions so need to look that up to see how it works. I've been diverted onto another project temporarily. I'll get back to you when I get back on project.

Steve

0 项奖励
811 次查看
bigmac
Specialist III

Hello,

One simple method is to create a union between the 32-bit value and a 4-element array.  For example,

typedef union {

  unsigned long lword;

  unsigned char a[4];

} TYPE_32BIT;


TYPE_32BIT val;

Access to 8-bit elements can be achieved with val.a[i], and access to the 32-bit quantity with val.lword.

Regards,

Mac

0 项奖励