Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to convert char array to vector of bytes (vector<byte>)

I have large array of char

char myCharArray[] = {
  0x9B,0x3E,0x34,0x87,0xFD,0x24,0xB4,0x64,0xBA,0x80,0x04,0xFD,
  0xDF,0x23,0x41,0xEE,0x00,0x00,0x00,0x00,0xAC,0xF9,0x8F,0x00,
  ...
}

How to convert myCharArray to vector<byte>

like image 892
Aaron Yordanyan Avatar asked Sep 01 '25 02:09

Aaron Yordanyan


1 Answers

You are allowed to inspect an array of char as an array of std::byte. So the most efficient solution would be:

#include <iterator> // for std::begin / end

std::vector<std::byte> v(
    reinterpret_cast<std::byte*>(std::begin(myCharArray)), 
    reinterpret_cast<std::byte*>(std::end(myCharArray))
);

This way, the vector knows up front how much memory to allocate and it can perform the copy via memcpy or a similar efficient routine instead of copying one byte after the other and having to reallocate multiple times in between.

EDIT:
Note that this code only works, because the return type of std::begin on a native array is guaranteed to be apointer. If myCharArray was e.g. a std::vector<char>, then std::begin/end would return an iterator (which may or may not be a native pointer). In that case, you would e.g. need to use myCharVector.data() and myCharVector.data() + myCharVector.size() to get pointers to the start and end of the array.

like image 187
MikeMB Avatar answered Sep 02 '25 17:09

MikeMB