-3

How do I convert a std::vector<uint8_t> to my custom defined structure?

For example I have

struct abc
{
    char a;
    char b;
    char c;
};

Does reinterpret_cast works in this?

I am a beginner in C++, but have good knowledge in C.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
md.jamal
  • 4,067
  • 8
  • 45
  • 108
  • 2
    You cannot convert a `std::vector` to a custom defined structure without introducing more or less [U.B.](https://stackoverflow.com/a/4105123/1505939) At least, you should [edit] and specify `std::vector` of what. (Though, I see few chances for an exception from the first sentence.) – Scheff's Cat Nov 19 '19 at 11:03
  • You have to implement a conversion function. For example: `abc from_vector(std::vector vec) { return abc{vec.at(0), vec.at(1), vec.at(2)}; }` – eike Nov 19 '19 at 11:05
  • At best, you could do a `reinterprete_cast` of `std::vector::data()`. `data()` provides the pointer to raw-data in `std::vector` which is granted to be contiguous. But, I still would be afraid about [U.B.](https://stackoverflow.com/a/4105123/1505939) although there are some special exceptions for `char*` and `unsigned char*` (to which `std::uint8_t` is probably an alias) in the standard. – Scheff's Cat Nov 19 '19 at 11:09
  • 1
    Concerning `reinterprete_cast`, I found a nice Q/A [SO: When to use reinterpret_cast?](https://stackoverflow.com/q/573294/7478597). – Scheff's Cat Nov 19 '19 at 11:13
  • There are some good answers here in the comments section – Lightness Races in Orbit Nov 19 '19 at 11:29
  • What do the `uint8_t`s come from and what do they represent? What do you expect the value `255` to become when converted to `char`? `-1`? `-127`? `-128`? Something else? – Ted Lyngmo Nov 19 '19 at 11:54

1 Answers1

0

You can't, at least not in a type safe and supported way. What you can do is roll your own copy method. In your case it would be as simple as memcpy(vec.data(), &struct, sizeof(struct)) assuming the vector is a direct translation (i.e 3 elements).

Pickle Rick
  • 808
  • 3
  • 6