简体   繁体   中英

How to access an array of 32 bit registers and read/write 16-bit upper and lower segments as a separate operation

I have a contiguous area of memory containing 320 bits divided into 10 independent "registers".

Once I create the memory area, I get back the address of the first register element.

At this point, I want to logically map an array of 32 bit structs containing a high and low part of the 32 bit number, then iterate through the array and write the upper and lower segments separately.

I already have a function that will split and inputted 32 bit number into two 16 bit parts, using a bit rotation scheme.

My question is, what is the best way to overlay the array of structs over the contiguous area.

The reason why I need to do this is that I am using an external library to talk to an embedded device, and the library has no concept of 32 bits, even the underlying device stores data in 32 bit registers.

First, make sure your struct is 32 bits as represented by the compiler. Check that sizeof(struct xxx) == 4 and play with the compiler packing options until it is (technically this ensures struct is 4 characters but it should be good enough)..

Second is to just create a pointer to object of the struct type and then assign it the address of the memory block. You will need an old fashioned type-cast operation to do that.

Something like (note the order of which is high and low and which bytes are which inside these will vary by hardware).

typedef struct {
   short high;
   short low;
} hilo;

hilo *registers = (hilo *) memPtr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM