convert struct to uint8_t array in C++

Issue

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

Solution

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);

Answered By – Some programmer dude

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published