简体   繁体   中英

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.

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.

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