Dan*_*mer 1 c c++ arrays string
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.
The C++ code is below:
#include <iostream>
#include <string>
typedef unsigned char BYTE;
int main(int argc, char *argv[])
{
BYTE byteArray[5] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
std::string s(reinterpret_cast<char*>(byteArray), sizeof(byteArray));
std::cout << s << std::endl;
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
Can anyone point me in the right direction?
C 中的字符串是零结尾的字节数组。因此,您需要做的就是将数组复制到一个新的缓冲区中,该缓冲区具有足够的空间用于尾随零字节:
#include <string.h>
#include <stdio.h>
typedef unsigned char BYTE;
int main() {
BYTE byteArray[5] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
char str[(sizeof byteArray) + 1];
memcpy(str, byteArray, sizeof byteArray);
str[sizeof byteArray] = 0; // Null termination.
printf("%s\n", str);
}
Run Code Online (Sandbox Code Playgroud)