Home > front end >  convert struct to uint8_t array in C
convert struct to uint8_t array in C

Time:11-10

I have a typedef struct with different data types in it. The number array has negative and non-negative values. How do I convert this struct in to a unint8t array in C on the Linux platform. Appreciate some help on this. Thank you. The reason I am trying to do the conversation is to send this uint8_t buffer as a parameter to a function.

typedef struct
{
  int enable;
  char name;
  int numbers[5];
  float counter;
};

appreciate any example on doing this. thank you

CodePudding user response:

Suggestion: use char*. For that type, C allows you to cast any pointer to it and use reinterpret_cast<char*>(&obj). (Assuming Obj obj;.)

If you need to use uint8_t* (and it's not a typedef to char*, you can allocate sufficient memory and do memcpy:

uint8_t buffer[sizeof(Obj)];
memcpy(buffer, &obj, sizeof(obj));

CodePudding user response:

For a plain old data structure like the one you show this is trivial:

You know the size of the structure in bytes (from the sizeof operator).

That means you can create a vector of bytes of that size.

Once you have that vector you can copy the bytes of the structure object into the vector.

Now you have, essentially, an array of bytes representation of the structure object.


In code it would be something like this:

struct my_struct_type
{
    int enable;
    char name;
    int numbers[5];
    float counter;
};

my_struct_type my_struct_object = {
    // TODO: Some valid initialization here...
};

// Depending on the compiler you're using, and its C   standard used
// you might need to use `std::uint8_t` instead of `std::byte`
std::vector<std::byte> bytes(sizeof my_struct_object);

std::memcpy(bytes.data(), reinterpret_cast<void*>(&my_struct_object), sizeof my_struct_object);
  • Related