将 0 存储在 unsigned char 数组中
storing 0 in a unsigned char array
我有一个这样的 unsigned char
数组:
unsigned char myArr[] = {100, 128, 0, 32, 2, 9};
我正在使用 reinterpret_cast
将其转换为 const char*
,因为我必须将 const char*
传递给方法。然后通过 grpc 和其他应用程序发送此信息(基于 erlang 的应用程序接收它并将其存储在 erlang Bin 中)。但我观察到的是 Erlang 应用程序只收到 <<100, 128>> 之后什么也没有。是什么原因造成的?这里的问题是字符数组中的 0
吗?有人可以解释如何处理 unsigned char
数组中的 0
吗?我确实阅读了很多答案,但没有一个能清楚地解释我的问题。
What could be causing this? Is it the 0 in the character array that is the problem here?
很有可能,是的。
可能指针传递给的函数之一被指定为接受指向空终止字符串的参数。您的数组恰好通过在字符串终止的索引 2 处包含空字符而以空字符终止。这样的函数通常只有在数组以 null 终止的情况下才会具有明确定义的行为,因此将指针传递给可能不包含 null 字符的任意二进制文件将非常危险。
Could someone explain how to handle the 0 in an unsigned char array?
不要将数组传递给期望以空字符结尾的字符串的函数。这包括大多数格式化输出函数和 <cstring>
中的大多数函数。该函数的文档应该提到 pre-conditions.
如果这些功能是您唯一的选择,那么您可以将二进制数据编码为文本格式,然后在另一端对其进行解码。二进制数据的常用文本编码是 Base64,尽管它不一定是最佳的。
我有一个这样的 unsigned char
数组:
unsigned char myArr[] = {100, 128, 0, 32, 2, 9};
我正在使用 reinterpret_cast
将其转换为 const char*
,因为我必须将 const char*
传递给方法。然后通过 grpc 和其他应用程序发送此信息(基于 erlang 的应用程序接收它并将其存储在 erlang Bin 中)。但我观察到的是 Erlang 应用程序只收到 <<100, 128>> 之后什么也没有。是什么原因造成的?这里的问题是字符数组中的 0
吗?有人可以解释如何处理 unsigned char
数组中的 0
吗?我确实阅读了很多答案,但没有一个能清楚地解释我的问题。
What could be causing this? Is it the 0 in the character array that is the problem here?
很有可能,是的。
可能指针传递给的函数之一被指定为接受指向空终止字符串的参数。您的数组恰好通过在字符串终止的索引 2 处包含空字符而以空字符终止。这样的函数通常只有在数组以 null 终止的情况下才会具有明确定义的行为,因此将指针传递给可能不包含 null 字符的任意二进制文件将非常危险。
Could someone explain how to handle the 0 in an unsigned char array?
不要将数组传递给期望以空字符结尾的字符串的函数。这包括大多数格式化输出函数和 <cstring>
中的大多数函数。该函数的文档应该提到 pre-conditions.
如果这些功能是您唯一的选择,那么您可以将二进制数据编码为文本格式,然后在另一端对其进行解码。二进制数据的常用文本编码是 Base64,尽管它不一定是最佳的。