Accessing individual bytes in a long int

cancel
Showing results for 
Search instead for 
Did you mean: 

Accessing individual bytes in a long int

Jump to solution
298 Views
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

Labels (1)
1 Solution
54 Views
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

View solution in original post

0 Kudos
5 Replies
54 Views
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 Kudos
54 Views
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

54 Views
Monica
Senior Contributor III

Yes, our dear friend bigmac ROCKS :smileygrin:

And so do you, keep the developing mood on!

Best regards,

Monica.

0 Kudos
54 Views
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 Kudos
55 Views
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

View solution in original post

0 Kudos