Convert C++ byte array to a C string

前端 未结 3 439
北海茫月
北海茫月 2021-01-24 01:34

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.

3条回答
  •  太阳男子
    2021-01-24 02:20

    C strings are null terminated, so the size of the string will be the size of the array plus one, for the null terminator. Then you could use memcpy() to copy the string, like this:

    #include 
    #include 
    #include 
    
    typedef unsigned char BYTE;
    
    int main(void)
    {
      BYTE byteArray[5] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
    
      // +1 for the NULL terminator
      char str[sizeof(byteArray) + 1];
      // Copy contents
      memcpy(str, byteArray, sizeof(byteArray));
      // Append NULL terminator
      str[sizeof(byteArray)] = '\0';
    
      printf("%s\n", str);    
      return EXIT_SUCCESS;
    }
    

    Output:

    Hello

    Run it online

提交回复
热议问题