Convert C++ byte array to a C string

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?

Kon*_*lph 9

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)

  • @tadman这是不公平的指责。标签说C,标题说C,问题的正文说C。我们(包括我!)全都跳到了C ++代码的视线,而忽略了像巴甫洛夫犬这样的标签和标题中对C的提及(因为我们已经习惯了期望这两种语言之间的标签错误),但是这个问题清楚地说明了为什么包括C ++代码以及它如何相关和合法。 (5认同)