Convert an array of bytes into a string using C++
By Steve Claridge on 2024-03-01.
Convert an array of bytes (uint8_t) into a string using C++.
#include <string>
#include <vector>
#include <iostream>
int main()
{
std::vector<uint8_t> b {0x68, 0x65, 0x6c, 0x6c, 0x6f };
std::string s(b.begin(), b.end());
std::cout << s << std::endl;
}
std::string
uses the default encoding of your location. I'm in the UK so the bytes I added in the array are using
ASCII encoding.
I compiled this on macOS using the following,
g++ -std=c++11 bytes.cpp
Note the flag to use C++11
if you run g++ without, it will default to C++03 which does not support brace initialization s
you will get this error
bytes.cpp:8:27: error: expected ';' at end of declaration
std::vector<uint8_t> b {0x68, 0x65, 0x6c, 0x6c, 0x6f };