简体   繁体   English

将C ++字节数组转换为C字符串

[英]Convert C++ byte array to a C string

I'm trying to convert a byte array to a string in C but I can't quite figure it out. 我正在尝试将字节数组转换为C语言中的字符串,但我不太清楚。

I have an example of what works for me in C++ but I need to convert it to C. 我有一个在C ++中对我有用的示例,但我需要将其转换为C。

The C++ code is below: C ++代码如下:

#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;
}

Can anyone point me in the right direction? 谁能指出我正确的方向?

Strings in C are byte arrays which are zero-terminated. C 中的字符串是零结尾的字节数组。 So all you need to do is copy the array into a new buffer with sufficient space for a trailing zero byte: 因此,您需要做的就是将数组复制到一个新的缓冲区中,该缓冲区具有足够的空间用于尾随零字节:

#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);
}

C strings are null terminated, so the size of the string will be the size of the array plus one, for the null terminator. C字符串以null终止,因此字符串的大小将是数组的大小加1(对于null终止符)。 Then you could use memcpy() to copy the string, like this: 然后,您可以使用memcpy()复制字符串,如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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 在线运行

Here is a demonstrative program that shows how it can be done. 这是一个演示程序,显示了如何完成它。

#include <stdio.h>
#include <string.h>

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". 否则,在调用memcpy之后,您必须“手动”添加终止零。

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. 当字符数组的大小远大于byteArray的大小时,应使用最后一个变体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM