1

I am consuming an api that returns a byte array as std::vector<int8>, but the rest of my application consumes byte arrays as std::vector<uint8>.

How can I convert std::vector<int8> to std::vector<uint8>?

273K
  • 29,503
  • 10
  • 41
  • 64
S-K'
  • 3,188
  • 8
  • 37
  • 50
  • Does [this reference](https://stackoverflow.com/a/1953708/1424875) offer a suitable starting point for you? – nanofarad Apr 29 '20 at 21:01

2 Answers2

3

You can use the constructor that accepts a range of iterators:

std::vector<uint8>(std::begin(signed_vec), std::end(signed_vec));

That said, in case you don't actually need a std::vector<uint8> object, but rather simply want to read a range of unsigned integers, you can reinterpret them instead:

uint8* ptr_beg = reinterpret_cast<uint8>(signed_vec.data());
uint8* ptr_end = ptr_beg + signed_vec.size();

Conversion between unsigned and signed versions of the same integer size is one of the rare cases where reinterpretation is well defined.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

You can traverse through each element and cast/push back to the new vector:

std::vector<int8> vec_int8 = returnedFromApi(); // assume it is filled
std::vector<uint8> vect_uint8;
for(int item = 0; item < vec_int8.size(); ++item)
{
  vect_uint8.push_back(static_cast<uint8>(vec_int8[item]));
}
Omid CompSCI
  • 1,861
  • 3
  • 17
  • 29