Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

How to convert a struct varible to uint8_t array in C?

Status
Not open for further replies.

jack1998

Junior Member level 2
Junior Member level 2
Joined
Oct 17, 2021
Messages
20
Helped
0
Reputation
0
Reaction score
0
Trophy points
1
Activity points
136
How to convert msg to uint8_t array msg_arr[8]?
Code:
typedef struct message_t
{
    uint16_t time;
    uint16_t lat; 
    uint8_t ns;
    uint16_t lon;
    uint8_t ew;
} message;

message msg;
msg.time = 0x1234;
msg.lat = 0x2122;
msg.ns = 'n';
msg.lon = 0x1834;
msg.ew = 'e';

uint8_t msg_arr[8];
 
Last edited by a moderator:

Hi,

general recommendation is to start with the biggest variables.
--> first all 32 bit variables then all 16 bit variables, then all 8 bit variables. This is to avoid "align" bytes.

Now it depends
* if you want to copy the struct into an 8 bit array
* or you just want to access the struct data

...( I´m no C specialist, thus - in doubt - rely on the answers of others)
COPY:
needs to be done byte by byte like:
Code:
byte0 = msg.time >>8;
byte1 = msg.time & 0xFF;
....

ACCESS:
could be done with pointers.
I guess something like this:

Code:
uint8_t * databyte;
uint8_t i;
databyte = (uint8_t *)&msg;

for (i = 0; i < sizeof(msg)8 ; i++)
{
   dosomethingwith databyte[i];
}

Klaus
 
Last edited:
You need to consider that depending on compler settings and processor hardware requirements the structure message_t isn't necessarily respectively even can't be packed. Thus type conversions of the discussed kind aren't safe and not necessarily portable.
 
Another option may be to use a union that contains both the struct and the array.
All of the usual caveats apply regarding compiler options, alignments, struct padding etc..
Susan
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top