I\'m trying to convert a byte array to a string in C but I can\'t quite figure it out.
I have an example of what works for me in C++ but I need to convert it to C.
Here is a demonstrative program that shows how it can be done.
#include
#include
typedef unsigned char BYTE;
int main(void)
{
BYTE byteArray[5] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
char s[sizeof( byteArray ) + sizeof( ( char )'\0' )] = { '\0' };
memcpy( s, byteArray, sizeof( byteArray ) );
puts( s );
return 0;
}
The program output is
Hello
Pay attention to that the character array is zero initialized. Otherwise after the call of memcpy you have to append the terminating zero "manually".
s[sizeof( s ) - 1] = '\0';
or
s[sizeof( byteArray )] = '\0';
The last variant should be used when the size of the character array much greater than the size of byteArray.