Convert byte array to string in C/C++
This post will discuss how to convert byte array to string in C/C++.
1. Using memcpy() function
The memcpy() function performs a binary copy of the arrays of POD (Plain Old Data) type like int, char, etc. It can be used to convert a byte array to a C-string, as follows. Note that C-Strings are NULL-terminated. Therefore, don’t forget to allocate space for a trailing NULL byte.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <cstring> int main() { unsigned char bytes[] = { 72, 101, 108, 108, 111 }; int n = sizeof(bytes); char chars[n + 1]; memcpy(chars, bytes, n); chars[n] = '\0'; // Null-terminate the string std::cout << chars; return 0; } |
Output:
Hello
2. Using String Constructor
To construct a C++ string from a byte array, use the string constructor. The constructor string (const char* b, size_t n) copies the first n characters from array b. The following is a simple example demonstrating its usage.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <string> int main() { const char bytes[] = { 72, 101, 108, 108, 111 }; std::string s(bytes, sizeof(bytes)); std::cout << s; return 0; } |
Output:
Hello
That’s all about converting byte array to string in C/C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)