jakebird451
jakebird451

Reputation: 2348

Struct to string and vice versa

I would like to take the memory generated from my struct and push it into a byte array (char array) as well as the other way around (push the byte array back into a struct). It would be even better if I could skip the string generation step and go directly to writing memory into the EEPROM. (Do not worry about the eeprom bit, I can handle that by reading & writing individual bytes)

// These are just example structs (I will be using B)
typedef struct {int a,b,c;} A;
typedef struct {A q,w,e;} B;

#define OFFSET 0 // For now

void write(B input)
{
  for (int i=0;i<sizeof(B);i++)
  {
    eepromWrite(i+OFFSET,memof(input,i));
  }
}

B read()
{
  B temp;
  for (int i=0;i<sizeof(B);i++)
  {
    setmemof(temp,i,eepromRead(i+OFFSET));
  }
  return temp;
}

This example I wrote is not supposed to compile, it was meant to explain my ideas in a platform independent environment.

PLEASE NOTE: memof and setmemof do not exist. This is what I am asking for though my question. An alternative answer would be to use a char array as an intermediate step.

Upvotes: 0

Views: 8879

Answers (1)

Adam Liss
Adam Liss

Reputation: 48310

Assuming your structures contain objects and not pointers, you can do this with a simple cast:

save_b(B b) {
  unsigned char b_data[sizeof(B)];
  memcpy(b_data, (unsigned char *) &b, sizeof(B));
  save_bytes(b_data, sizeof(B));
}

Actually, you shouldn't need to copy from the structure into a char array. I was just hoping to make the idea clear.

Be sure to look into #pragma pack, with determines how the elements in the stuctures are aligned. Any alignment greater than one byte may increase the size unnecessarily.

Upvotes: 1

Related Questions