Convert byte array to string in C++

A byte array is an array of bytes, which are units of data typically used to represent a character such as a letter, number, or symbol in a computer’s memory. In C++, a byte array can be represented using an array of elements of type char, unsigned char, or uint8_t.

The article here discusses various ways to convert a given array of bytes into a string.

Table Of Contents

Method 1: Using std::string

The std::string class is a standard C++ class that provides a convenient way to manipulate and work with strings. It is part of the C++ Standard Template Library (STL).

To convert a byte array to a string using the std::string class we use the following algorithm.

Advertisements

Algorithm

  1. We create a vector of bytes with the elements ‘H’, ‘e’, ‘l’, ‘l’, ‘o’.
  2. The std::string constructor is then used to create a string str by specifying a range of elements from the bytes vector giving the start and the end pointer of the vector as the input.
  3. Finally, the resultant string is printed and we get the output as “Hello”.

Program

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    // Create a byte array
    vector<uint8_t> bytes = { 'H', 'e', 'l', 'l', 'o' };

    // Convert the byte array to a string
    string str(bytes.begin(), bytes.end());

    cout << str << endl;

    return 0;
}

Output

Hello

Alternatively, we can also give the ASCII value of the bytes as input in the bytes array, the output string will remain the same.

Program

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    // Create a byte array
    vector<uint8_t> bytes = { 72, 101, 108, 108, 111 };

    // Convert the byte array to a string
    string str(bytes.begin(), bytes.end());

    cout << str << endl;

    return 0;
}

Output

Hello

Time Complexity – O(N)

  • N is the size of the bytes array. Since we travel from the start to the end of the bytes vector.

Note

  1. The elements of the byte array are of type uint8_t, which is an unsigned 8-bit integer type. This is equivalent to the char type in C++ and is used to represent a single byte. The byte array could also be created using the char type instead of uint8_t.
  2. Both of these examples assume that the byte array contains ASCII characters. If the array contains characters that are not ASCII, you may need to use a different method of conversion, such as the std::wstring_convert class.
  3. In case of an array instead of vector as input you need to provide the array name and size of the array inside the string class as arguments “string str(bytes, sizeof(bytes))”

Method 2: Using memcpy()

memcpy is a function in C and C++ that copies a block of memory from a source location to a destination location.

Here is the method of how you can use memcpy to convert a byte array to a string in C++:

Algorithm

  1. Create a new character array (c_str) with the same size as the bytes vector.
  2. Copy the contents of the bytes vector into it using std::memcpy().
  3. The character array is then null-terminated and used to construct a std::string object, which is stored in the result variable.
  4. Print the string result onto the console.

Program

#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

int main()
{
    vector<uint8_t> bytes { 72, 101, 108, 108, 111 };

    char* c_str = new char[bytes.size() + 1];
    memcpy(c_str, bytes.data(), bytes.size());
    c_str[bytes.size()] = '
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
int main()
{
vector<uint8_t> bytes { 72, 101, 108, 108, 111 };
char* c_str = new char[bytes.size() + 1];
memcpy(c_str, bytes.data(), bytes.size());
c_str[bytes.size()] = '\0';
string result(c_str);
delete[] c_str;
cout << result << endl;
}
'; string result(c_str); delete[] c_str; cout << result << endl; }

Output

Hello

Time Complexity – O(N)

  • N is the size of the bytes array
  • memcpy has a time complexity of O(n) and the program also needs to allocate and deallocate the character array, which takes constant time.

Method 3: Using stringstream

stringstream is a stream class in C++ that allows you to read from and write to strings as if they were input/output streams. It is defined in the sstream header and is part of the std namespace.

We can use stringstream to convert an input byte array to a string as follows:

Algorithm
1. We first declare a byte array and initialize it with some values.
2. Then, we create a std::stringstream object and iterate over the bytes array inserting each byte into the stream.
3. We use the str function to extract the string from the stringstream and print it to the console.

Program

#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

int main() {
  // Define a byte array
  vector<uint8_t> bytes = { 72, 101, 108, 108, 111 };

  // Create a stringstream object
  stringstream ss;

  // Iterate over the byte array and insert each byte into the stringstream
  for (uint8_t byte : bytes) {
    ss << byte;
  }

  // Extract the resulting string from the stringstream
  string str = ss.str();

  // Print the resulting string
  cout << str << endl;

  return 0;
}

Output

Hello

Time Complexity – O(N)

  • N is the size of the bytes array
  • Since we iterate through all the elements of the bytes array to insert them into the stream.

Summary

In this article, we learned how to convert a byte array given as input to a string using the std::string class, memcpy() function and the stringstream class.

Advertisements

Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top