Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a uint8_t array to a struct

I have this array

uint8_t *buffer = "JOHN:DOE:010119:M:FOO:BAR";

and I want to copy it field by field to data structure

typedef struct{
  uint8_t firstName[5];
  uint8_t pad1;
  uint8_t lastName[4];
  uint8_t pad2;
  uint8_t dateOfBirth[7];
  uint8_t pad3;
  uint8_t genre;
  uint8_t pad4;
  uint8_t car[4];
  uint8_t pad5;
  uint8_t phone[4];
  uint8_t pad6;
}DataStructTypeDef;

Let's say that all lengths are fixed (eg. firstName is always composed of 4 characters, lastName of 3 etc ...)

I used this approach:

DataStructTypeDef foo;
memcpy((void *)&foo, (void *)buffer, sizeof(DataStructTypeDef));

When I try to print dateOfBirth it shows the whole array starting from 01012019 like this

int main(void)
{
  DataStructTypeDef foo;
  memcpy((void *)&foo, (void *)buffer, sizeof(DataStructTypeDef));
  printf("%s", foo.dateOfBirth); // It prints 010119:M:FOO:BAR
//printf("%s", foo.dateOfBirth); // Expected value 010119
  return 0;
}
like image 950
Pryda Avatar asked Jan 28 '26 15:01

Pryda


2 Answers

Since the char array members you are copying are not null terminated, printf("%s", will not know when it has encountered the end of each string.

This can be controlled in printf by limiting the amount of characters that print...

For example:

printf("%.*s", (int)sizeof(foo.dateOfBirth), foo.dateOfBirth);

An equivalent would be:

printf("%.6s", food.dateOfBirth);

.* specifies the "precision" of characters you want to print. So in your case, dateOfBirth = precision/size 6.

like image 90
static_cast Avatar answered Jan 30 '26 06:01

static_cast


  1. Modify your structure

Add an extra byte to each field to accommodate the '\0' character. For e.g. use

uint8_t firstName[5];

instead of

uint8_t firstName[4];
  1. Parse the fields individually and end each field with '\0'

Instead of copying the entire buffer in one go, copy the elements one by one. Since, the size of each field is fixed, the offset from the start of the buffer is fixed and this makes the job of parsing easier.

like image 44
sri Avatar answered Jan 30 '26 05:01

sri